【问题标题】:Why does passing $null to a parameter with AllowNull() result in an error?为什么使用 AllowNull() 将 $null 传递给参数会导致错误?
【发布时间】:2022-02-09 07:45:02
【问题描述】:

考虑以下代码:

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

Test -ComputerName $null

基于the official documentation for AllowNull,我期望$ComputerName 可以是[string]$null。但是,运行上述代码会导致以下错误:

[14,24: Test] 无法将参数绑定到参数“ComputerName”,因为它是空的 字符串。

为什么在这种情况下为 $ComputerName 传递 $null 不起作用?

【问题讨论】:

  • 我不能给你一个明确的解释,但在我看来 $null 被转换为一个空字符串,由于参数类型,因此不包含在验证属性中了。使用 AllowEmptyString() 代替工作。我认为这是一个文档错误。

标签: powershell parameters nullable


【解决方案1】:

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

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

如果你想为 [string] 参数传递$null,你应该使用[NullString]::Value

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

【讨论】:

  • 只有一个警告,据我所知,tihs 在 2.0 上不起作用
【解决方案2】:

如果您计划允许空值空字符串,您还需要添加[AllowEmptyString()] 属性。

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

Test -ComputerName $null

【讨论】:

    【解决方案3】:

    如前所述,当转换为 [string] 时,$null 变为空字符串 ("")。为避免这种情况,一种选择是将参数作为对象键入 - 然后在主体测试中首先输入 $null,然后检查 $MyParam.GetType().Name 是否为“String”。

    【讨论】:

      猜你喜欢
      • 2012-02-20
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      相关资源
      最近更新 更多