为什么将$ null传递给带有AllowNull()的参数会导致错误?

为什么将$ null传递给带有AllowNull()的参数会导致错误?

问题描述:

考虑以下代码:

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

Test -ComputerName $null

基于我期望的AllowNull 官方文档$ComputerName可以是[string]$null.但是,运行上面的代码会导致以下错误:

Based on the official documentation for AllowNull I was expecting that $ComputerName could either be [string] or $null. However, running the above code results in the following error:

[14,24:测试]无法将参数绑定到参数'ComputerName',因为它为空 字符串.

[14,24: Test] Cannot bind argument to parameter 'ComputerName' because it is an empty string.

在这种情况下,为什么不为$ComputerName传递$ null呢?

Why doesn't passing $null for $ComputerName work in this case?

$null,当转换为[string]时,返回空字符串,而不是$null:

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

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

如果要为[string]参数传递$null,则应使用[NullString]::Value:

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

[string][NullString]::Value -eq $null # True
Test -ComputerName ([NullString]::Value)