PoshBytes: Test (Path) Before You Leap

PoshBytes: Test (Path) Before You Leap

Use Test-Path to check whether files, folders, and registry paths exist before your script wanders confidently into a wall.

This post is a companion for the short PoshBytes: Test (Path) Before You Leap.

Welcome to PoshBytes, where today we ask PowerShell a simple question: does this thing exist, or are we about to have a very confident error message?

Check for a file

Test-Path returns true or false, which is wonderfully boring, and boring is exactly what we want before deleting, copying, importing, or otherwise touching anything important.

# Check if a file exists
Test-Path -Path '.\servers.csv'

Use it in logic

This is where Test-Path becomes useful. Instead of assuming the file exists, check first and respond like a responsible adult with a keyboard.

# Only import the file if it exists
if (Test-Path -Path '.\servers.csv') {
    Import-Csv -Path '.\servers.csv'
}
else {
    Write-Warning 'The servers.csv file was not found.'
}

Check folders too

It also works with folders, which is handy when your script needs to create a directory without throwing an error because it already exists.

# Create a folder only if it does not already exist
$path = 'PS:\Reports'

if (-not (Test-Path -Path $path)) {
    New-Item -Path $path -ItemType Directory
}

Deleting files safely

A lot of people do this:

# Delete the file and ignore errors
Remove-Item -Path '.\oldreport.csv' -ErrorAction SilentlyContinue

Don’t do that.

Technically… yes, that will allow your script to continue, if the file doesn’t exist.

But deletes can fail for a whole host or reason. The file could be locked, permissions could be wrong, or your script could be attempting to delete something that Windows is emotionally attached to.

So instead, check first.

# Check if the file exists before deleting it
if (Test-Path -Path '.\oldreport.csv') {
    Remove-Item -Path '.\oldreport.csv'
}
else {
    Write-Host 'File does not exist.'
}

Now your script clearly handles the “file missing” scenario separately from actual delete failures, which makes troubleshooting much easier later.

Check the registry

And finally Test-Path is not just for files. You can also check things like the registry too.

# Check if a registry path exists
Test-Path -Path 'HKLM:\Software\Microsoft\PowerShell'

Wrap Up

• Test-Path checks whether a path exists.
• It works with files, folders, and other PowerShell providers.
• It returns true or false.
• Use it before reading, writing, copying, deleting, or creating paths.
• Your future self will thank you, probably using fewer swear words.

Leave a Reply

Your email address will not be published. Required fields are marked *