Test-Path | Taking on PowerShell one cmdlet at a time | Weekly Blog

Share this post:

This is a part of an on-going blog series written by Adam Gordon. Each week, Adam will walk you through a PowerShell command, showing you when and how to use each one. This week, Adam covers Test-Path.

When to use Test-Path

The Test-Path cmdlet determines whether all elements of the path exist.

It returns $True if all elements exist and $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 or leaf element.

 

How to use Test-Path

Test a path:

Test-Path -Path “C:\Documents and Settings\AdamG”

This command checks whether all elements in the path exist, that is, the C: directory, the Documents and Settings directory, and the AdamG directory.

NOTE: If any are missing, the cmdlet returns $False. Otherwise, it returns $True.

Test-Path

 

Test the path of a profile:

Test-Path -Path $profile
Test-Path -Path $profile -IsValid

These commands test the path of the PowerShell profile.

The first command determines whether all elements in the path exist.

The second command determines whether the syntax of the path is correct.

These commands use $profile, the automatic variable that points to the location for the profile, even if the profile does not exist.

Test-Path

 

Check whether there are any files besides a specified type:

 Test-Path -Path “C:\azure\mytemplates\*” -Exclude *.json

The command uses the –Path parameter to specify the path.

The asterisk at the end of the path indicates the contents of the mytemplates directory.

The command specifies the –Exclude parameter to specify files that will be omitted from the evaluation.

Test-Path

 

Check paths in the Registry:

Test-Path -Path “HKLM:\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell”

Tests whether the registry path of the Microsoft.PowerShell registry key is correct on the system. If PowerShell is installed correctly, the cmdlet returns $True.

Test-Path

 

Test-Path -Path “HKLM:\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell\ExecutionPolicy”

Test-Path does not work correctly with all PowerShell providers.

For example, you can use Test-Path to test the path of a registry key, but if you use it to test the path of a registry entry, it always returns $False, even if the registry entry is present.

Test-Path

Test-Path

 

Test if a file is newer than a specified date:

Test-Path $pshome\PowerShell.exe -NewerThan “July 13, 2018”

This command uses the –NewerThan dynamic parameter to determine whether the “PowerShell.exe” file on the computer is newer than “July 13, 2018”.

NOTE: The -NewerThan parameter works only in file system drives.

Test-Path

Need PowerShell training? Check out ITProTV’s PowerShell online IT training courses.

Leave a Reply

Your email address will not be published. Required fields are marked *