The Test-Path cmdlet in PowerShell returns $true if all the elements of a file or directory path exist, otherwise $false. It can also tell whether the file was updated after or before the particular date. It determines whether the syntax of a path is valid or not.
Following are the parameters used in the Test-Path cmdlet:
This parameter is used to specify those items which are omitted by this cmdlet. Wildcard characters are accepted in this parameter.
This parameter is used to specify the path to be tested. If you use the path which includes the spaces, enclose it in quotation marks. Wildcard characters are accepted in this parameter.
This parameter is used to specify a filter in the format or language of the provider.
This parameter is used to specify the path which is tested by this cmdlet. In this parameter, the wildcard characters are accepted.
-IsValid is used to test the syntax of a path instead of checking the elements of a path. When this parameter is used in the cmdlet, the cmdlet returns the $True if the syntax of a path is valid, otherwise $False.
This parameter is used to specify the path to be tested. Unlike the -Path parameter, the value of this parameter is used exactly as it is typed.
This parameter is used to specify the time as an object of DateTime.
This parameter is also used to specify the time as an object of DateTime.
This parameter is used to determine the type of final element which is specified in the path. When this parameter is used in the cmdlet, it returns $True if the element is of a specified type, otherwise returns $False.
For this parameter, following are the acceptable values:
- Leaf: It is an element or a value which does not contain the other elements.
- Container: It is an element or a value which contains the other elements, such as registry key or directory.
- Any: It is an element which is either a leaf or a container.
Example 1: Check the path in the file system.
The command in this example checks whether all the elements in the path of file system exist or not. If any of the elements are missing in the path, then the command returns $False, otherwise $True. In this example, all elements in the path are correct, so it returns True.
Example 2: Check the path in the registry key
The command, in this example, checks whether the path of Microsoft.PowerShell registry key is correct or not. If it is correct, then the command returns $True, otherwise $False.
Example 3: Test a file is older than the specified date
Both the commands in this example uses the -olderThan parameter to check whether the k.txt file is older than the specified date.
The first command returns $False because it is last created or modified after the 10 December 2019. And the second command returns $True because it is last created or modified before the 15 December 2019.
The -olderThan parameter is used only with the file system.