我试图理解PowerShell中的空变量赋值,请参阅下面的代码示例:
[Bool]$result = $null
Cannot convert value "" to type "System.Boolean". Boolean parameters accept only Boolean values and numbers, such as $True, $False, 1 or 0.
这是有道理的。现在使用函数时:
function Test-Function {
[CmdletBinding()]
Param (
)
[Bool]$result = $null
Write-Output -InputObject "Value of 'result' is: $result"
Write-Output -InputObject "Type is: $($result.GetType())"
}
使用
Test-Function -ErrorAction Stop
运行上述函数时,将返回以下输出:
Value of 'result' is: False
Type is: bool
为什么在函数内部将
$null
分配给 $result
时,行为会有所不同?
在 Windows 11 上使用 PowerShell 5.1
该行为来自
[CmdletBinding()]
属性,这使其成为“高级功能”。
CmdletBinding 属性是函数的一个属性,使函数像用 C# 编写的已编译 cmdlet 一样运行。它提供对 cmdlet 功能的访问。
本质上,您有 2 条不同的错误消息告诉您同一件事 - 布尔值不是“可为空” -
$true
和 $false
是唯一受支持的值。