What is the Test-Path cmdlet in PowerShell?

Overview

The Test-Path cmdlet is used to check if all the elements provided in the path exist.

Syntax

Test-Path -Path "provide path here"

Parameters

  • Path: This is a mandatory parameter, which accepts the path.
  • NewerThan: This parameter checks whether the file is newer than the given date.

Return value

This cmdlet returns a boolean value.

Example

#!/usr/bin/pwsh -Command
#test if all elements exist in path are valid
Write-Output "Test if path '/usr/bin/' exists "
Test-Path /usr/bin/
#test if all elements exist in path are valid
Write-Output "Test with wrong path '/usr/bin/sdflkdsj'"
Test-Path /usr/bin/sdflkdsj
#test if the file newer than given date
Write-Output "Test if the pwsh file is newer than April 13, 2021"
Test-Path /usr/bin/pwsh -NewerThan "April 13, 2021"

Explanation

  • Line 5: We test if the given path is valid or not using the cmdlet Test-Path. This returns True, as the path is valid.
  • Line 9: We test giving the wrong path at the end. It returns False because the path is invalid.
  • Line 13: We check if the pwsh file is newer than the given date "April 13, 2021" by passing it to the NewerThan parameter.

Free Resources