为什么将$ null传递给带有AllowNull()的参数会导致错误? [英] Why does passing $null to a parameter with AllowNull() result in an error?

查看:121
本文介绍了为什么将$ 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)

这篇关于为什么将$ null传递给带有AllowNull()的参数会导致错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆