How to use the ValidateScript attribute in PowerShell function?



The ValidateScript attribute is to validate the script before entering inside the function. For example, let say you want to validate the path of the file, validate the remote computer connectivity, etc. We will take here remote server connectivity example.

Without the ValidateScript attribute, we would have written the script as shown below.

Function Check-RemoteServer {    param (       [string]$Server    )    if(Test-Connection -ComputerName $Server -Count 2 -Quiet -ErrorAction Ignore) {       Write-Output "$server is reachable"    } else {       Write-Output "$Server is unreachable"    } }

Output

PS C:\> Check-RemoteServer -Server asde.asde asde.asde is unreachable PS C:\> Check-RemoteServer -Server Google.com Google.com is reachable

With the ValidateScript attribute, script will be reduced to few lines of code.

Function Check-RemoteServer {    param (       [ValidateScript({Test-Connection -ComputerName $_ -Count 2 -       Quiet}, ErrorMessage = "Remote Server unreachable")]       [string]$Server    )    Write-Output "$Server is reachable" }

Output

PS C:\> Check-RemoteServer -Server Google.com Google.com is reachable PS C:\> Check-RemoteServer -Server asde.asde Check-RemoteServer: Cannot validate argument on parameter 'Server'. Remote Server unreachable
Updated on: 2020-09-19T09:10:22+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements