 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements
 