- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
- Related Articles
- How to use the ValidateRange attribute in PowerShell function?
- How to use the ValidateSet Attribute in PowerShell function?
- How to use the ValidateCount attribute in PowerShell Function?
- How to use the ValidateLength attribute in PowerShell?
- How to use function Alias in PowerShell?
- Explain the Mandatory Attribute in PowerShell Advanced Function.
- How to use the formmethod attribute in HTML?
- How to use the required attribute in HTML?
- How to use stopwatch in PowerShell?
- How to use the ErrorActionPreference variable in PowerShell?
- How to use the ErrorAction parameter in PowerShell?
- How to use the tree command in PowerShell?
- How to use the Timeout command in PowerShell?
- How to add help in the PowerShell function?
- How to add an attribute to the XML file using Powershell?

Advertisements