Validating user input in shell script

Rated 3.91/5 based on 614 customer reviews

If the value of the $Event Date parameter is a Date Time object and it’s later than now, the function writes a nice sentence with the date to the console or host program. I can never remember this, so I use an ISE snippet or copy it from about_functions_advanced_parameters.

But, if the value of $Event Date is not a Date Time object, or it’s not a future date, the function generates an error. But aside from the syntax, Validate Script is easy to use.

In particular, Validate Script lets you write a script block to test the conditions that the values must satisfy. The syntax of this thing looks like a sampler of Windows Power Shell enclosures.

Windows Power Shell runs the validation script on the parameter values and, if the script returns $False, it throws a terminating error. There’s a square bracket “[“ or two “]”, a pair of parentheses “( )” and even some curly braces “”. But once you get over the syntax, you realize that putting the parameter value validation into the parameter definition means that you don’t need to test the parameter value in your script.

The Get-Event Date function has a $Event Date parameter. At line:15 char:26 Get-Event Date -Event Date (Get-Process Power Shell)                          ~~~~~~~~~~~~~~~~~~~~~~~~ Category Info         : Invalid Data: (:) [Get -Event Date], Parameter Binding Argument Transformation Exception Fully Qualified Error Id : Parameter Argument Transformation Error, Get-Event Date Now, let’s get Windows Power Shell to test the other date condition for us. Its parameter is enclosed in parentheses: [Validate Script( )] and the parameter value is a script block, complete with curly braces: [Validate Script()].And, in particular, errors that cannot provide very helpful error messages?Personally, I prefer scripts that optimize the user experience, instead of the authoring experience.When you send the wrong type of parameter value to a cmdlet, Windows Power Shell tries to convert the value to the right type.It returns an error only when its attempts to convert fail. If you ask Windows Power Shell 3.0 how many items are in an empty object, it tells you 0, even though empty objects don’t have a Count or Length property.

Leave a Reply