Why does passing $null to a parameter with AllowNull() result in an error?

前端 未结 2 1091
情书的邮戳
情书的邮戳 2020-12-22 04:40

Consider the following code:

function Test
{
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory=$true)]
        [AllowNull()]
        [String         


        
相关标签:
2条回答
  • 2020-12-22 05:12

    $null, when converted to [string], return empty string not $null:

    [string]$null -eq $null # False
    [string]$null -eq [string]::Empty # True
    

    If you want to pass $null for [string] parameter you should use [NullString]::Value:

    [string][NullString]::Value -eq $null # True
    Test -ComputerName ([NullString]::Value)
    
    0 讨论(0)
  • 2020-12-22 05:20

    You also need to add the [AllowEmptyString()] attribute if you plan on allowing nulls and empty strings.

    function Test
    {
        [CmdletBinding()]
        param
        (
            [parameter(Mandatory=$true)]
            [AllowNull()]
            [AllowEmptyString()]
            [String]
            $ComputerName
        ) 
        process{}
    }
    
    Test -ComputerName $null
    
    0 讨论(0)
提交回复
热议问题