Because in PowerShell there is no
[ValidateNotNullOrWhiteSpace()]
Parameter attribute, is it better to use
[ValidateNotNullOrEmpty()]
as the parameter attribute, then look for whitespace inside the function, or should i use
[ValidateScript({ -not ([String]::IsNullOrWhiteSpace($_)) })]
as the parameter attribute.
im not sure what the NotNullOrEmpty attribute is really good for, because 99% of time, i don't want this to ever work:
My-Cmdlet -ParameterName " "
but because " " is still a string, it will pass the NotNullOrEmpty attribute.
The [ValidateNotNullOrEmpty()]
is good for doing exactly what it says it will.
To answer your first question, I would use the [ValidateScript(...)]
method you outlined.
One thing to keep in mind is that the error message for [ValidateScript()]
is usually terrible and doesn't help the end user. As a workaround, you can do this:
[ValidateScript( {
![String]::IsNullOrWhiteSpace($_) -or throw 'Your string is null or contains whitespace'
} )]
You can also include an exception class in the throw like:
throw [System.ArgumentException]'Blah blah whitespace'
-or throw
syntax worksBoolean operators in PowerShell work like many other languages in that they do "shortcutting". They stop evaluating the expression as soon as the outcome is definite. So for $false -and $(sleep -min 10)
it doesn't take 10 minutes, because the second expr is never evaluated.
Similarly, $true -or $(something)
will not evaluate the second, because it will always be true if the first expression is true.
So in this case it's similar. ValidateScript
needs a bool. If the condition we care about is true, it will stop there. If it's not, the second expression is evaluated, and since that's a throw
it will just fail, but in this case you can control the failure message (and exception class if you want).
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