Skip to content

PowerShell File Input/Output

How to use PowerShell cmdlets like Test-Path, Get-Item, and Get-ChildItem to validate, inspect, and manipulate files and directories using .NET objects (FileInfo, DirectoryInfo).

File Input/Output (I/O) in PowerShell enables scripts to interact with filesystem storage, inspecting metadata, reading and writing data streams, and manipulating directory structures. Built on top of the FileSystem provider, PowerShell represents files and directories as strongly typed .NET objects (FileInfo and DirectoryInfo) rather than raw text paths, giving you immediate access to file sizes, timestamps, and attributes without manual string parsing.

File I/O Cmdlet Overview

PowerShell provides a cohesive suite of cmdlets adhering to the standard Verb-Noun convention for interacting with filesystem items and content streams.

Operation Category Cmdlet Description Detailed Reference
Validation Test-Path Checks whether a file or directory exists. This page
Inspection Get-Item Retrieves an object representing the item itself. This page
Enumeration Get-ChildItem Lists child items inside a directory or container. This page
Creation New-Item, Out-File Creates new empty files or directory containers. Creating Files
Reading Get-Content, Import-Csv Reads text line-by-line or as a single raw string. Reading From Files
Writing Set-Content, Out-File, Export-Csv Overwrites or creates files with new text data. Writing To Files
Appending Add-Content, Out-File -Append Appends text content to the end of a file. Appending To Files
Deletion Remove-Item Deletes files, directories, or registry paths. Deleting Files
Moving Move-Item Moves files or directories to new destinations. Moving Files
Copying Copy-Item Copies items from a source path to a destination. Copying Files
Renaming Rename-Item Changes the name or extension of an existing item. Renaming Files

Validating Paths with Test-Path

The Test-Path cmdlet verifies whether all elements of a specified path exist on the filesystem. It returns a simple boolean: $true if the target exists, or $false if it does not, which is the standard way to validate a file or folder's existence before attempting to read, write, or delete it.

Test-Path -Path "C:\Windows\notepad.exe"
Test-Path -Path "C:\NonExistentFile.txt"
True
False

Checking Path Type with -PathType

By default, Test-Path returns $true whether the path points to a file or a directory. To check for a specific container type, use the -PathType parameter:

-PathType Value Description
Leaf Verifies that the path points to a file (the end of a path tree).
Container Verifies that the path points to a directory or folder.
Any (Default) Returns $true if either a file or a folder exists at the path.
Test-Path -Path "C:\Windows" -PathType Container
Test-Path -Path "C:\Windows\notepad.exe" -PathType Leaf
True
True

Where:

  • -PathType Container checks specifically that the path is a directory.
  • -PathType Leaf checks specifically that the path is a file, not a folder.

Practical Use: Guarding File Operations

$filePath = "C:\Config\settings.json"

if (Test-Path -Path $filePath) {
    $content = Get-Content -Path $filePath -Raw
    Write-Output "File loaded successfully."
} else {
    Write-Warning "Configuration file not found: $filePath"
}
WARNING: Configuration file not found: C:\Config\settings.json

Inspecting Items: Get-Item vs. Get-ChildItem

Understanding the difference between Get-Item and Get-ChildItem is fundamental when working with the PowerShell FileSystem provider.

  • Get-Item retrieves the specified item itself, such as a file or directory.
  • Get-ChildItem retrieves the items contained within the specified directory.
  • Aliases for Get-ChildItem include dir, ls, and gci.

For example, let's assume the following structure:

C:\Projects contains:

  • app.js
  • package.json
  • src\

The commands behave differently:

Command Result
Get-Item "C:\Projects" Returns a DirectoryInfo object representing C:\Projects
Get-ChildItem "C:\Projects" Returns the items inside C:\Projects: FileInfo for app.js, FileInfo for package.json, and DirectoryInfo for src\

Get-Item Basics

Get-Item retrieves an object representing a single file, folder, or other provider item at a specified path, without looking inside it.

Get-Item -Path "C:\Windows\notepad.exe"
    Directory: C:\Windows

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a---           5/7/2022   1:18 AM         210432 notepad.exe

Where:

  • -Path specifies the exact location of the item to retrieve.
  • The returned object is a System.IO.FileInfo instance, exposing properties like .Length, .LastWriteTime, and .Extension.
(Get-Item "C:\Windows\notepad.exe").Extension
.exe

When targeting a file, you can inspect its properties directly:

Get-Item -Path "$env:SystemRoot\notepad.exe" |
    Format-List -Property Name, Length, LastWriteTime, Attributes
Name          : notepad.exe
Length        : 210432
LastWriteTime : 5/7/2026 1:18:24 AM
Attributes    : Archive

Get-ChildItem Basics

Get-ChildItem lists the contents of a directory, including files and subfolders, rather than the directory itself.

Get-ChildItem -Path "C:\Windows" | Select-Object -First 5
    Directory: C:\Windows

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----         12/7/2019  10:51 AM                addins
d-----          4/6/2026   8:18 AM                appcompat
d-----         3/30/2026   7:31 PM                apppatch
d-----         9/27/2026   4:54 PM                AppReadiness
d-r---         3/19/2026   8:03 PM                assembly

Where:

  • Items with d at the start of Mode are directories; items with -a are regular files.
  • Without any parameters beyond -Path, both files and folders are returned together.

Common Get-ChildItem Parameters

Parameter Purpose
-Recurse Include all subdirectories, not just the immediate level
-Filter Restrict results using a simple wildcard pattern (fast)
-Include / -Exclude Restrict results using more flexible pattern matching (used with -Recurse)
-File Return only files, excluding folders
-Directory Return only folders, excluding files
-Force Include hidden and system files
Get-ChildItem -Path "C:\Windows" -Filter "*.exe" -File | Select-Object -First 3
    Directory: C:\Windows

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----         3/22/2026   9:36 AM          93696 bfsvc.exe
-a----         3/22/2026   9:36 AM        6089584 explorer.exe
-a----         3/22/2026   9:43 AM        1065984 HelpPane.exe
Get-ChildItem -Path "C:\Windows" -Filter "*.log" | Select-Object -First 2
    Directory: C:\Windows

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----         3/23/2026   6:18 PM           2271 DtcInstall.log
-a----         3/30/2026   7:20 PM          32205 iis.log

Practical Example: Directory and File Validation Script

The following script combines Test-Path, Get-Item, and Get-ChildItem to validate an application staging directory, check container metadata, and summarize contained log files.

param (
    [string]$TargetFolder = "$env:TEMP"
)

if (-not (Test-Path -Path $TargetFolder -PathType Container)) {
    Write-Error "The specified directory '$TargetFolder' does not exist."
    exit 1
}

$FolderItem = Get-Item -Path $TargetFolder

$ChildFiles = Get-ChildItem -Path $TargetFolder -File -ErrorAction SilentlyContinue

[PSCustomObject]@{
    FolderName     = $FolderItem.Name
    FullPath       = $FolderItem.FullName
    CreatedOn      = $FolderItem.CreationTime.ToString("yyyy-MM-dd")
    TotalFileCount = ($ChildFiles.Count)
    DirectoryValid = $true
}

Where:

  • Test-Path -Path $TargetFolder -PathType Container ensures the target is a valid folder before proceeding.
  • Get-Item -Path $TargetFolder retrieves the DirectoryInfo object for the target folder.
  • Get-ChildItem -Path $TargetFolder -File retrieves only file items inside the folder.
  • [PSCustomObject] wraps the folder metadata and child file metrics into a clean, structured object.

Execute the script from the console:

./inspect-storage-staging.ps1 -TargetFolder "C:\Windows"
FolderName     : Windows
FullPath       : C:\Windows
CreatedOn      : 2019-12-07
TotalFileCount : 22
DirectoryValid : True

Additional Example: Guarded Configuration Reader

param (
    [string]$ConfigPath = "$env:TEMP\BackupStaging\manifest.json"
)

[PSCustomObject]@{
    TargetTested = $ConfigPath
    FolderExists = (Test-Path -Path (Split-Path $ConfigPath) -PathType Container)
    FileExists   = (Test-Path -Path $ConfigPath -PathType Leaf)
}
Navigation