Share this post:This blog post is part of an ongoing series by Adam Gordon. Adam will walk through each PowerShell command every week, explaining when and how to use them. Adam will be covering Test-Path this week.
When to use Test Path
The Test-Path cmdlet verifies that all elements of the path are present.
It returns $True if all elements are present and $False, if none are.
It can also tell if the path syntax is valid, and whether it leads to a container, terminal, or leaf element.
How to use Test Path
Try a path:
Test-Path –Path “C” -Documents and SettingAdamG
This command checks whether all elements of the path are present, that is, the C directory, the Documents and Settings director, and the AdamG director.
NOTE: If there are any missing, the cmdlet returns $False. It returns $True otherwise.
Check out the profile’s path:
Test-Path -Path $profileTest-Path -Path $profile -IsValid
These commands test the PowerShell profile’s path.
The first command determines if all elements on the path are present.
The second command will determine if the syntax of the path has been correctly entered.
These commands use $profile as the automatic variable that points at the location of the profile.
Verify if there are other files than the one you have requested.
Test-Path -Path “C:\azure\mytemplates\*” -Exclude *.json
To specify the path, the command uses the parameter -Path
The mytemplates directory contents are indicated by the asterisk at end of path
The command specifies the parameter -Exclude to specify files that will not be evaluated.
You can find the Registry’s paths here:
Test-Path -Path “HKLM:\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell”
This test verifies that the registry path for the Microsoft.PowerShell registry keys is correct. If PowerShell has been installed correctly, the cmdlet returns $True.
Test-Path -Path “HKLM:\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell\ExecutionPolicy”
Test-Path is not compatible with all PowerShell providers.
You can use Test-Path, for example, to test the path to a registry key. However, if you use it in order to test the paths to a registry entry’s path, it will always return $False even if the registry entries are present.
Check if the file is older than a given date.
Test-Path $pshome\PowerShell.exe -NewerThan “July 13, 2018”
This command uses the dynamic parameter -NewerThan to determine if the PowerShell.exe file on the computer has changed since July 13, 2018.
NOTE: The NewerThan parameter is only applicable to file system drives.
Do you need PowerShell training? ITProTV offers PowerShell online IT training courses.