在 PowerShell 函数中将 null 赋给变量

问题描述 投票:0回答:1

我试图理解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

powershell
1个回答
0
投票

该行为来自

[CmdletBinding()]
属性,这使其成为“高级功能”。

CmdletBinding 属性是函数的一个属性,使函数像用 C# 编写的已编译 cmdlet 一样运行。它提供对 cmdlet 功能的访问。

取自 CmdletBindingAttribute 文档

本质上,您有 2 条不同的错误消息告诉您同一件事 - 布尔值不是“可为空” -

$true
$false
是唯一受支持的值。

© www.soinside.com 2019 - 2024. All rights reserved.