Passing null to a mandatory parameter to a function

后端 未结 4 1290
暗喜
暗喜 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:11

    First, add an AllowNull attribute:

    Function Foo
    {
        Param
        (
            [Parameter(Mandatory = $true)][AllowNull()][string] $Bar
        )
    
        Write-Host $Bar
    }
    

    Then, when you call the function, be aware that $null when used for [string] becomes an empty string, not a null reference. Therefore (since PowerShell 3 (2012)) use [NullString]::Value like this:

    Foo -Bar ([NullString]::Value)
    

    See the documentation for System.Management.Automation.Language.NullString class.


    EDIT: From the call site this appears to work, but at soon as you reach the Write-Host cmdlet within the function, $Bar will again have become an empty string. See comments below. We must conclude that PowerShell insists strings must be like that. Note that NullString (which has been useful to me in other cases) in its documentation only promises to be helpful when passing null "into a .NET method".

提交回复
热议问题