How to use the ValidateScript attribute in PowerShell function?

PowerShellMicrosoft TechnologiesSoftware & Coding

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
raja
Published on 19-Sep-2020 09:09:24
Advertisements