Validating user input in shell script
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.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.Input validation, in its simplest terms, is just putting some kind of constraint on the kind of information the user can pass to your script.Perhaps your script exposes a -Computer Name parameter to enable the user of your script to run it against different computers.
To limit the number of possible scenarios, it's a best practice to incorporate some kind of input validation into your code.
In Windows Power Shell 3.0, if you send it a collection of object and ask for a property that the collection doesnâ€™t have, Windows Power Shell checks to see if the objects in the collection have that property and, if they do, it returns the property value. Many scripts, including those weâ€™ve seen in these esteemed Games, have elaborate try-catch syntax to capture errors and create a pleasant user experience.
So, given that background, should we encourage scripting techniques that throw errors to users, instead of making them successful?
But I thought Iâ€™d take a minute and demystify it â€“ and discuss an issue that it raises about when input should be rejected.
Letâ€™s start with a quick description of Validate Script and its siblings. Validate Script and its siblings are parameter validation attributes.
Search for validating user input in shell script:
Before we get to the details, letâ€™s talk about why youâ€™d want to use something like this. Instead, the Windows Power Shell engine tests the parameter value and you can use the script to do scripty things. Hereâ€™s a silly function that will serve as our example. Validate Script is enclosed in square brackets: [Validate Script].