Should I use [ValidateNotNullOrEmpty ()] and then look for spaces in the function, or should I use [ValidateScript (...)]?

Because PowerShell doesn't

[ValidateNotNullOrWhiteSpace()]

      

Parameter attribute, better to use

[ValidateNotNullOrEmpty()]

      

as a parameter attribute, then look for a space inside the function or should I use

[ValidateScript({ -not ([String]::IsNullOrWhiteSpace($_)) })]

      

as a parameter attribute.

im not sure if the NotNullOrEmpty attribute is really good because 99% of the time, I don't want this to ever work:

My-Cmdlet -ParameterName " "

      

but since "" is still a string, it will pass the NotNullOrEmpty attribute.

+3


source to share


1 answer


[ValidateNotNullOrEmpty()]

good for doing what he says.

To answer your first question, I would use the method [ValidateScript(...)]

you described.

It should be borne in mind that the error message is [ValidateScript()]

usually dire and does not 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 the exception class in the throw, for example:

throw [System.ArgumentException]'Blah blah whitespace'

      

+6


source







All Articles