I'd like to call a PowerShell script this way :
script.ps1 -path mypath\to\files\ -days 6 -hours 0
To validate the command line arguments, I can either do it by hand, either rely on the param
syntax :
Param (
[Parameter(Mandatory=$true )] [string] $path,
[Parameter(Mandatory=$false)] [int] $days,
[Parameter(Mandatory=$false)] [int] $hours
)
If I use the param
syntax :
the param definition must be the first line in the script (excluding comments). Okay, not a problem for me
in case of incorrect parameters, I can't catch the error (for example to display a custom error message)
I'd like to display a custom error message when the script is called with wrong parameters.
Is it possible, and how, to catch the exception in case of parameter error ?
The examples are for functions (simple and advanced) but the same idea should work for scripts with
param
as well:Or
The following test:
in both cases produces the same output:
you can do that with the param syntax, if you add a string-type dummy-parameter with the property "ValueFromRemainingArguments". Then you can check this dummy-parameter in your script and take appropriate actions, e.g.:
So okay, it is not possible to use
param
AND to catch the related exceptions.In the
Begin
block you can always do further validation on the parameters but if the parameter is wrong, I think you wouldn't want to continue execution. That is, you'd want to throw a terminating error. Here's an example:That said, I'm not sure that's any better than using PowerShell's built-in parameter validation functionality e.g.:
A possible workaround is to wrap your actual function in another one. Something similar to a private/public relation. Example:
If you are working on a module you could take a look here how to export your public functions and hide the private ones: Export Powershell Functions