I'm studying powershell functions and its validate parameters. However I can't understand if they are really useful.
I make a simple example.
function get-choice(
[parameter(Mandatory=$true)][String][ValidateSet('Y','N')]$choice
)
{return $choice}
get-choice k
This function returns me this error:
get-choice : Impossibile convalidare l'argomento sul parametro 'choice'. L'argomento "k" non appartiene al set "Y,N" specificato dall'attributo ValidateSet. Fornire un argomento inclu
so nel set ed eseguire di nuovo il comando.
In riga:6 car:11
+ get-choice <<<< k
+ CategoryInfo : InvalidData: (:) [get-choice], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,get-choice
If I don't specify a valid set of values I can check them within my code:
function get-choice2(
[parameter(Mandatory=$true)][String]$choice
) {
if($choice -ne 'y' -and $choice -ne 'n') {
write-host "you must choose between yes and no"
return
}
return $choice
}
get-choice2 k
and I get a more friendly message:
you must choose between yes and no
First of all I'd like to know if it's possible to customize error message using validateset. Then I hope that someone could explain why I'd have to prefer first approach. Thanks in advance.
Some reasons why to use standard validation:
if
statementreturn
statement)Check Better error messages for PowerShell ValidatePattern - post by @jaykul. You will see how you could customize the error message. It's a little bit developer oriented, but worth reading it.
The advantage to using parameter validation is that you don't have to do it yourself. That's a lot of boring, boilerplate code that no longer needs to be written and tested. A big win in my book, even though it results in less-friendly error messages.
You can write some help documentation for your function, so that user's can type help get-choice2
, and see an explanation for what that parameter means:
function get-choice(
[parameter(Mandatory=$true)][String][ValidateSet('Y','N')]$choice
)
{
<#
.SYNOPSIS
Gets the user's choice.
.PARAMETER choice
The choice. Must be Y or N.
#>
return $choice
}
Run help about_comment_based_help
for more details, or see the MSDN documentation.
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