Passing null to a mandatory parameter to a function

后端 未结 4 1288
暗喜
暗喜 2021-01-03 21:18

Effectively my problem comes down to this:

I can\'t have a function with a mandatory parameter and pass $null to that parameter:

Function Foo
{
    P         


        
4条回答
  •  北海茫月
    2021-01-03 22:00

    You should be able to use the [AllowEmptyString()] parameter attribute for [string] parameters and/or the [AllowNull()] parameter attribute for other types. I've added the [AllowEmptyString()] attribute to the function from your example:

    Function Foo {
        Param
        (
            [Parameter(Mandatory = $true)]
            [AllowEmptyString()]  <#-- Add this #>
            [string] $Bar
        )
    
        Write-Host $Bar
    }
    
    Foo -Bar $null
    

    For more info, check out the about_Functions_Advanced_Parameters help topic.

    Be aware that PowerShell will coerce a $null value into an instance of some types during parameter binding for mandatory parameters, e.g., [string] $null becomes an empty string and [int] $null becomes 0. To get around that you have a few options:

    • Remove the parameter type constraint. You can check for $null in your code and then cast into the type you want.
    • Use System.Nullable (see the other answer for this). This will only work for value types.
    • Rethink the function design so that you don't have mandatory parameters that should allow null.

提交回复
热议问题