Categories

Path cmdlets: 1 Test-Path

From some recent feedback it seems that the *Path cmdlets aren’t as well known as I thought.

PS> Get-Command *path | select name

Name
----
Convert-Path
Join-Path
Resolve-Path
Split-Path
Test-Path

 

We’ll start with test-path

 

The Test-Path cmdlet determines whether all elements of the path exist. It returns TRUE ($true) if all elements exist and FALSE ($false) if any are missing. It can also tell whether the path syntax is valid and whether the path leads to a container or a terminal (leaf) element.

 

The basic use is to test if a file exists

PS> Test-Path -Path c:\scripts\test1.csv
True

 

This can be taken further to do some processing

PS> if (Test-Path -Path c:\scripts\test1.csv){Remove-Item -Path c:\scripts\test1.csv}
PS> Test-Path -Path c:\scripts\test1.csv
False

OR

if (!(Test-Path -Path c:\scripts\test1.csv)){Throw "File not found"}

 

We can also test is a path’s syntax is valid

PS> Test-Path -Path c:\scripts\test1.csv -IsValid
True

PS> Test-Path -Path http://go.microsoft.com/fwlink/?LinkID=113418 -isvalid
False

 

We can also test if the path leads to a file or a container

 

This tests a file

PS> Test-Path -Path c:\scripts\test2.csv
True
PS> Test-Path -Path c:\scripts\test2.csv -PathType Leaf
True
PS> Test-Path -Path c:\scripts\test2.csv -PathType Container
False

 

This tests a folder

PS> Test-Path -Path c:\scripts
True
PS> Test-Path -Path c:\scripts -PathType leaf
False
PS> Test-Path -Path c:\scripts -PathType container
True

 

We can work with the registry keys

PS> Test-Path -Path HKLM:\Software\Microsoft
True

 

Test-Path does not work correctly with all Windows PowerShell providers. For example, you can use Test-Path to test  the path to a registry key, but if you use it to test the path to a registry entry, it always returns FALSE, even if the registry entry is present.

Leave a Reply