There are a number of cmdlets for working with paths
PS> Get-Command *path | select Name
Name
—-
Convert-Path
Join-Path
Resolve-Path
Split-Path
Test-Path
Test-Path is the one I probably use most
PS> Test-Path -Path "C:\Users\Richard\Documents\PowerShell in Practice\TODO.txt"
True
PS> Test-Path -Path "C:\Users\Richard\Documents\PowerShell in Practice\Chapter1.docx"
False
It returns a Boolean – true if the path is found and false if not. BTW don’t worry about the missing chapter it’s somewhere else.
One of my common uses for this is to test if a file exists before doing something
PS> if (Test-Path -Path "C:\Users\Richard\Documents\PowerShell in Practice\TODO.txt"){Write-Host "Found it"}
Found it
PS> if (Test-Path -Path "C:\Users\Richard\Documents\PowerShell in Practice\chapter1.docx"){Write-Host "Found it"}
else{Write-Host "Its gone"}
Its gone
We can also test if the path points to a file or a directory
PS> Test-Path -Path "C:\Users\Richard\Documents\PowerShell in Practice\TODO.txt" -PathType "leaf"
True
PS> Test-Path -Path "C:\Users\Richard\Documents\PowerShell in Practice\TODO.txt" -PathType "container"
False
The path cmdlets also work in other providers as we shall see later