I have a function that accepts a string array parameter of files and I would like to use Test-Path (or something else) to ensure that all the files in the string array parameter exists. I would like to do this in the parameter declaration if possible.
Is this possible?
The Test-Path cmdlet determines whether all elements of the path exist. It returns $True if all elements exist and $False if any are missing. It can also tell whether the path syntax is valid and whether the path leads to a container or a terminal or leaf element.
The first option for validating parameters in PowerShell is the ValidateSet-attribute. It allows you to specify a set of valid values for a parameter or variable and additionally enables tab completion in the shell.
Parameter and variable validation attributes. Validation attributes direct PowerShell to test the parameter values that users submit when they call the advanced function. If the parameter values fail the test, an error is generated and the function isn't called.
You can use ValidateScript
param(
[parameter()]
[ValidateScript({Test-Path $_ })]
[string[]]$paths
)
For more documentation on parameter validation visit about_Functions_Advanced_Parameters
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With