【问题标题】:Why does '$true -eq "string"' returns $true? [duplicate]为什么'$true -eq "string"' 返回 $true? [复制]
【发布时间】:2014-12-20 03:50:06
【问题描述】:

在 powerShell 中,您使用“-eq”运算符将布尔值与字符串进行比较,它总是返回与我之前比较时相同的布尔值。

例如

$shouldBeFalse = $true -eq "hello"
$shouldBeTrue = $false -eq "hello"

变量 $shouldBeFalse 是 $true。 变量 $shouldBeTrue 是 $false。

我不得不使用“Equals”方法:

$shouldBeFalse = $true.Equals("hello")

在这种情况下,$shouldBeFalse 是 $false。

但是为什么会返回带有布尔值的 -eq 运算符呢?

【问题讨论】:

    标签: string powershell boolean compare equals


    【解决方案1】:

    PowerShell 将始终使用左侧参数的类型进行评估。由于左侧有一个布尔值,PowerShell 将尝试将“Hello”转换为布尔值,以便使用 -eq 进行评估。

    因此,在您的情况下,"hello" 被转换为布尔值 [bool]"hello",它的计算结果为 True,因为它不是零长度字符串。如果您反其道而行之,您会看到类似的行为。

    PS C:\> "hello" -eq $true
    False
    
    PS C:\> [bool]"hello" -eq $true
    True
    

    在第一种情况下,$true 被转换为字符串“true”,它不等于“hello”,因此为 false。在第二种情况下,我们将“hello”转换为布尔值,因此-eq 将比较布尔值。由于提到的原因,这评估为 True。

    另一个很好的解释来自这个答案,它可能会将您的问题标记为重复:Why is $false -eq "" true?

    【讨论】:

      猜你喜欢
      • 2021-11-10
      • 2019-02-08
      • 2015-06-22
      • 2013-05-11
      • 2015-10-07
      • 1970-01-01
      • 2013-11-10
      • 2017-07-29
      • 1970-01-01
      相关资源
      最近更新 更多