Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should i use [ValidateNotNullOrEmpty()] and then look for whitespace in the function, or use [ValidateScript(...)]?

Tags:

powershell

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.

like image 454
tomohulk Avatar asked Apr 27 '15 19:04

tomohulk


1 Answers

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'

Why the -or throw syntax works

Boolean 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).

like image 150
briantist Avatar answered Nov 15 '22 03:11

briantist