
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Use 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