DevOps | Scripts | Automation

Powershell

How to add the Path validation in the PowerShell script?

To add the path validation in the PowerShell function, we can use the ValidateScript parameter which validates the script before running the actual commands. First, let’s see how we can use the function without the ValidateScript parameter.

We use the Test-Path command to test the path of the file, registry, certificates, etc. We will use the same concept in this script.

param(
    [Parameter(Mandatory)]
    [String]$Path
)

if (Test-Path $Path) {
    Write-Host "Provided path is valid" -f Green
}
else {
    Write-Host "Provided path is invalid" -f Red
}

Output:

If we need to use this Path validation code inside the param block then we can use as below so the script will be terminated itself when the path is invalid.

param(
    [Parameter(Mandatory)]
    [ValidateScript({
        if(Test-Path $_){return $true}
        else{ throw "$_ path is invalid" }
    })]
    [String]$Path
)

Write-Host "Script execution started" -f Green

Output:

This is the very simple check which was applied at the start of the script and terminates the script if it doesn’t match the path. This is useful when we are providing the file as an input and the entire script is dependent on the input file.