- 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 validate the path with the PowerShell function parameter?
To validate the file or folder path inside the PowerShell function parameter, we need to use the ValidateScript command. Generally, we write the script as below to validate the path.
function Validate-Path{ param( [parameter(Mandatory)] [String]$Path ) if(Test-Path $Path) {Write-Output "Path is valid"} else{Write-Output "Path is invalid"} }
Output
PS C:\> Validate-Path -Path C:\Temp Path is valid
We can add similar functionality inside the function parameter with the validatescript argument so the script will throw the error initially at the parameters check. See below,
function Validate-Path{ param( [parameter(Mandatory)] [ValidateScript({ if(Test-Path $_){$true} else{throw "Path $_ is not valid"} })] [String]$Path ) Write-Output "Executing Script further" }
Output
Valid Path
PS C:\> Validate-Path -Path C:\Temp Executing Script further
InValid Path
PS C:\> Validate-Path -Path C:\Temp223 Validate-Path : Cannot validate argument on parameter 'Path'. Path C:\Temp223 is not valid At line:1 char:21 + Validate-Path -Path C:\Temp223 + ~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Validate-Path], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,Validate-Path
In the above example, if the path is valid, the script will continue execution but if the path is not valid then it will throw an exception and the script is terminated.
Advertisements