gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 00:22:50 26 4
gpt4 key购买 nike

考虑以下代码:

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] Cannot bind argument to parameter 'ComputerName' because it is an empty string.



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

最佳答案

$null,当转换为[string]时,返回空字符串而不是$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)

关于powershell - 为什么将$ null传递给带有AllowNull()的参数会导致错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31843443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com