r/PowerShell • u/AlternativeSir1423 • Jun 05 '26
Question Does parameter "Mandatory" attribute imply "ValidateNotNullOrEmpty"
I ran into a curious case, and I can't find documentation to explain the case clearly. I am hoping someone can give me a hint.
I found out that PowerShell does not allow a null or empty string to be a parameter to this test function:
funcion test {
param (
[Parameter(Mandatory = $true)]
[string []] $a
)
$a
}The following test cases all gave me errors
test ''
test @( '' )
test @( '', '' )
test @( 'a', '' )
test @( '', 'a' )
test $null
test ( $null, 'a' )
test ( 'a', $null )The error message is one of these two
Cannot bind argument to parameter 'a' because it is an empty string.
Cannot bind argument to parameter 'a' because it is null.I also tried just
testthen press enter, and still got the error message.
Note that I did not add "ValidateNotNullOrEmpty" to the parameter, but PowerShell was behaving like I did. I can't find any documentation that describes the link between Mandatory and ValidateNotNullOrEmpty.
If anyone can clear up this confusion for me, I'd much appreciate it. TIA.
View all comments
Show parent comment
3
u/raip Jun 05 '26
It's not required - but it's best practice. With the ValidateNotNull() attribute, when you pass in a collection with a null or empty string, you get this error message instead:
This is much clearer than the standard
or