r/PowerShell • • 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

test

then 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.

12 Upvotes

11 comments sorted by

View all comments

Show parent comment

1

u/MonkeyNin Jun 09 '26

There are a couple of situations where you do not want parameterbinding to throw, even if they are blank. For that kind of situation, [String]::IsNullOrEmpty and [String]::IsNullOrWhitespace are great.

You can pass anything, even empty arrays to it. Basically the latter is testing if something stringlike is blank like whitespace 0 length.

For example you might use them for

profile functions where you want a different kind of usability that normal cmdlets. Or non-fatal errors that aren't actually errors like generating html

function WriteList { 
    # Silly example that writes html bulleted lists
    param( 
        [Parameter()]
        [string[]] $List
    )

    # first build a <li> pair for all items
    [string] $html = foreach( $item in $list ) { 
        # We want to ignore strings that have invisible characters
        if( [string]::IsNullOrWhiteSpace( $item ) ) {
            continue
        }    
        "`n`t<li>${item}</item>"
    }

    # If $html has zero items, don't print html
    # otherwise write html for unordered lists
    if( $html ) { 
        "<ul>${html}</ul>"
    }
}

Example Output

WriteList 'bob', 'jen', 'cat'                        
WriteList @(0..3 + $null + $null + 'af' + $null )    

# test ofr "empty" values and lists with blank items.
# No output is correct )
WriteList @()             # no output
WriteList @( $Null )      # no output

<ul>
    <li>bob</li>
    <li>jen</li>
    <li>cat</li>
</ul>


<ul>
     <li>0</item>
     <li>1</item>
     <li>2</item>
     <li>3</item>
     <li>af</item></ul>