Powershell -eq与compare-object

时间:2016-12-08 15:44:54

标签: powershell operators compareobject

为什么Compare-Object按预期工作,-EQ无法准确比较字符串数组?

我有一个PowerShell脚本,它填充了一个字符串数组,并使用-EQ运算符来测试预期值 - 这总是失败 - 我认为以下代码说明了问题

    # Setting up 4 Lists - $Lists1 2 and 3 should be identical and $List4 differs
    [string[]]$List1  = "AA","BBB"
              $List2  = $List1

    [string[]]$List3  = "AA"
              $List3 += "BBB"

    [string[]]$List4  = $List3
              $List4 += "CCCC"

    "--------"
    "Checking for Equality of the Lists using the -EQ comparison operator (why do all fail--- when only List4 should fail)"
    "--------"
    if ($List1 -eq $List1) {"List 1 and 1 are equal"} else {"List 1 and 1 are NOT equal"} 
    if ($List1 -eq $List2) {"List 1 and 2 are equal"} else {"List 1 and 2 are NOT equal"} 
    if ($List1 -eq $List3) {"List 1 and 3 are equal"} else {"List 1 and 3 are NOT equal"} 
    if ($List1 -eq $List4) {"List 1 and 4 are equal"} else {"List 1 and 4 are NOT equal"} 
    ""
    ""
    "--------"
    "Checking using Compare-object (operates as expected - only List4 Differs)"
    "--------"
    if ((compare-object $List1 $List1) -eq $null) {"List 1 and 1 are equal"} else {"List 1 and 1 are NOT equal"} 
    if ((compare-object $List1 $List2) -eq $null) {"List 1 and 2 are equal"} else {"List 1 and 2 are NOT equal"} 
    if ((compare-object $List1 $List3) -eq $null) {"List 1 and 3 are equal"} else {"List 1 and 3 are NOT equal"} 
    if ((compare-object $List1 $List4) -eq $null) {"List 1 and 4 are equal"} else {"List 1 and 4 are NOT equal"} 

2 个答案:

答案 0 :(得分:0)

让我用示例

向您解释
$a1=@(1,2,3,4,5)
$b1=@(1,2,3,4,5,6)
$c = Compare-Object -ReferenceObject (1..5) -DifferenceObject (1..6) -PassThru

$ c将为6。

比较对象的作用

其中-EQ仅检查左侧是否等于右侧。它产生一个布尔值。

示例

$DNS = (Test-Connection www.google.com -quiet)
If($DNS -eq "True") {Write-Host "The internet is available"} 
ElseIf($DNS -ne "True") {Restart-Service dnscache}

答案 1 :(得分:0)

取自this answer - 这当然值得一读,因为它非常好地解释了你的问题:

当在两个数组变量之间使用-eq运算符时,事情会有所不同。事实上,PowerShell将枚举左侧上的数组,并将每个项目与右侧整个的数组进行比较。如果没有匹配项,结果将是一系列匹配项什么都不

Compare-Object将在两个数组之间返回差异数组,或者在数组相等时返回$null。更准确地说,结果数组将包含每个项目的对象,该对象仅存在于一个数组中而不存在于另一个数组中。