PowerShell - Determine if file or directory exists using Test-Path

by
Jeremy Canfield |
Updated: April 26 2023
| PowerShell articles
Test-Path can be used to determine if files or directories exist. In this example, True is returned because file C:\Users\JohnDoe\example.txt does exist.
C:\Users\JohnDoe> Test-Path -Path 'C:\Users\JohnDoe\example.txt'
True
In this example, False is returned because file C:\Users\JohnDoe\bogus.txt does NOT exist.
C:\Users\JohnDoe> Test-Path -Path 'C:\Users\JohnDoe\bogus.txt'
False
In this example, True is returned because directory C:\Users\JohnDoe does exist.
C:\Users\JohnDoe> Test-Path -Path 'C:\Users\JohnDoe'
True
In this example, False is returned because directory C:\Users\bogus does NOT exist.
C:\Users\JohnDoe> Test-Path -Path 'C:\Users\bogus'
False
This is often used with an if statement to do something based on whether or not the file or directory exists.
if (Test-Path -Path 'C:\Users\JohnDoe\example.txt') {
Write-Host "example.txt exists"
}
else {
Write-Host "example.txt does NOT exist"
}
Did you find this article helpful?
If so, consider buying me a coffee over at