Introduction
Test-Path helps you check if a file, folder, or other item exists before you try to use it. This avoids errors and makes your scripts smarter.
Test-Path -Path <string> [-PathType <string>] [-IsValid] [-Credential <PSCredential>] [-Exclude <string[]>] [-Include <string[]>] [-Filter <string>] [-UseTransaction] [<CommonParameters>]
Test-Path -Path 'C:\Users\Public\Documents\file.txt'Test-Path -Path 'C:\Users\Public\Documents' -PathType Containerif (Test-Path -Path 'C:\temp') { Write-Output 'Folder exists' } else { Write-Output 'Folder missing' }
param(
[string]$CheckPath = 'C:\Windows'
)
if (Test-Path -Path $CheckPath) {
Write-Output "The path '$CheckPath' exists."
} else {
Write-Output "The path '$CheckPath' does not exist."
}Test-Path 'C:\Users\Public' check?log.txt exists in the current directory using Test-Path?$path = 'C:\Windows\System32'
if (Test-Path $path) { 'Exists' } else { 'Not Found' }if (Test-Path -Path 'D:\Data') {
Write-Host 'Folder found'
} else {
Write-Host 'Folder missing'
}$files = @('file1.txt', 'file2.txt', 'file3.txt')
foreach ($f in $files) {
if (Test-Path $f) { Write-Output $f }
} correctly loops over each file, checks existence with Test-Path, and outputs the file name. $files = @('file1.txt', 'file2.txt', 'file3.txt')
foreach ($f in $files) {
if (Test-Path -Exists $f) { Write-Output $f }
} uses invalid -Exists parameter. $files = @('file1.txt', 'file2.txt', 'file3.txt')
foreach ($f in $files) {
if (Test-Path $files) { Write-Output $f }
} incorrectly tests the whole array each time. $files = @('file1.txt', 'file2.txt', 'file3.txt')
foreach ($f in $files) {
if (Test-Path $f) { Write-Host 'File exists' }
} outputs a generic message, not the file name.Pass the test and this pattern moves unknown