[PowerShell] How to validate if a path exists

1 minute read

Test-path cmdlet is one of the most frequently used when working with PowerShell. The function of Test-path cmdlet is to validate if a file or folder exists in a directory. If the following cmdlet is run, the result will return True or False.

    $customerFile = "C:\CustomerList\*"
    Test-Path $customerFile

Below is an example on how to use Test-path cmdlet.


Scenario 1: Given that I have a Customer file
When I want to read the content of the file
And I want to manipulate the data in the file
Then I should check if the file exists in the path before I could read and manipulate the data in the file.


Let use below file structure for the scenario that we have:
  + C:\CustomerList
     - CustomerListA.txt
     - CustomerListB.txt
     - CustomerListC.txt
     - HousingList.txt
     - FolderA
  + C:\CarList
     - CarListA.txt
     - CarListB.txt
     - CarListC.txt

Example:

    $customerFile = "C:\CustomerList\*"
    if (Test-Path $customerFile) {
        Write-Host "The Customer file path exist" 
    } else {
        Write-Host "The Customer file path does not exist"         
    } 

There are a few variables that can be used to further defined the result using Test-path cmdlet. Below are some of them which I use most of the time.

Parameter Description
-Include list specific files and folders based on the given value
-Exclude list all files and folders except for the value given
-PathType verify folders exist -PathType container
verify files exist E.g : -PathType leaf
-OlderThan list files/folder that older than given date. E.g : -OlderThan ‘20/08/2021’
-NewerThan list files/folder that newer than given date. E.g : -NewerThan ‘01/08/2021’

Example:

    $customerFile = "C:\CustomerList\*"
    If (Test-Path $customerFile -Include "CustomerListA.txt”) {
        Write-Host "The Customer File path exist" 
    } else {
        Write-Host "The Customer File path does not exist"         
    }