【问题标题】:PowerShell - How to tell if two objects are identicalPowerShell - 如何判断两个对象是否相同
【发布时间】:2018-05-14 13:28:57
【问题描述】:

假设您有两个相同的对象(意味着它们分别具有相同的属性和相同的值)。

你如何测试相等性?

示例

$obj1 & $obj2 相同

这是我尝试过的:

if($obj1 -eq $obj2)
{
    echo 'true'
} else {
    echo 'false'
}
# RETURNS "false"

if(Compare-Object -ReferenceObject $obj1 -DifferenceObject $obj2)
{
    echo 'true'
} else {
    echo 'false'
}
# RETURNS "false"

编辑

这不相同

【问题讨论】:

  • 使用Compare-Object -IncludeEqual 否则它只会告诉你不同之处。否则,如果没有返回,则成功。
  • @TheIncorrigible1 不是我想要的。如果我向$obj1 添加属性,-IncludeEqual 仍将返回$true
  • 检查我的答案。它应该按您的预期工作。
  • 不要发布图片输出。使用代码格式并将输出粘贴为文本。
  • @KolobCanyon 我没有否决你的问题。也许其他人因为您使用图片而不是粘贴输出文本而投反对票? (但不是我;我认为这是一个好问题。)

标签: powershell object if-statement conditional equality


【解决方案1】:

您可以比较两个PSObject 对象的属性和值是否相等,方法是使用Compare-Object 比较两个PSObject 对象的Properties 属性。示例:

if ( -not (Compare-Object $obj1.PSObject.Properties $obj2.PSObject.Properties) ) {
  "object properties and values match"
}
else {
  "object properties and values do not match"
}

如果你想在函数中使用它:

function Test-PSCustomObjectEquality {
  param(
    [Parameter(Mandatory = $true)]
    [PSCustomObject] $firstObject,

    [Parameter(Mandatory = $true)]
    [PSCustomObject] $secondObject
  )
  -not (Compare-Object $firstObject.PSObject.Properties $secondObject.PSObject.Properties)
}

【讨论】:

    【解决方案2】:

    我建议使用Compare-Object 来完成这项任务:

    Function Test-Objects
    {
        Param(
        [Parameter(Mandatory,Position=0)]
        [PSCustomObject]$Obj1,
        [Parameter(Mandatory,Position=1)]
        [PSCustomObject]$Obj2
        )
    
        [Void](Compare-Object -ReferenceObject $Obj1.PSObject.Properties -DifferenceObject.PSObject.Properties $Obj2 -OutVariable 'Test')
    
        ## Tests whether they are equal, no return = success
        If (-not $Test)
        {
            $True
        }
        Else
        {
            $False
        }
    }
    

    PS C:\> $Obj1 = [PSCustomObject]@{
        Property1 = 'Value1'
        Property2 = 'Value2'
        Property3 = 'Value3'
        Property4 = 'Value4'
        Property5 = 'Value5'
    }
    PS C:\> $Obj2 = [PSCustomObject]@{
        Property1 = 'Value1'
        Property2 = 'Value2'
        Property3 = 'Value3'
        Property4 = 'Value4'
        Property5 = 'Value5'
    }
    PS C:\> Test-Objects $Obj1 $Obj2
    True
    PS C:\> $Obj2 | Add-Member -MemberType 'NoteProperty' -Name 'Prop6' -Value 'Value6'
    PS C:\> Test-Objects $Obj1 $Obj2
    False
    

    【讨论】:

    • 假设您这样做...$obj1 | Add-Member -NotePropertyName 'NewProperty' -NotePropertyValue 'NewValue'...如果您运行上面的代码,它仍然认为$obj1 等于$obj2,即使它们不是。我刚刚测试过
    • Compare-Object 使用ToString() 进行比较 - 这是不可靠的。例如,使用$obj1 = [pscustomobject] @{ 'a' = '5'; 'b' = 7; }; $obj2 = [pscustomobject] @{ 'c' = '6'; 'b' = 7; } - 它表示它们是平等的。见:stackoverflow.com/a/18346380/1244910
    • @KolobCanyon 实际上是错误的。在我的测试(v2、v5)中,它工作正常。
    • 当你可以简单地写-not $Test时为什么要if (-not $Test) { $true } else { $false }?
    • @Bill_Stewart 我太专注于他的问题示例,但你是绝对正确的
    【解决方案3】:

    如果您想测试每个对象属性的相等性,一次一个,以便比较和对比两个对象并查看哪些单独的部分不同,您可以使用以下函数,改编自这篇文章如何compare all properties of two objects in Windows PowerShell

    Function Compare-ObjectProperties {
        Param(
            [PSObject]$leftObj,
            [PSObject]$rightObj 
        )
    
        $leftProps = $leftObj.PSObject.Properties.Name
        $rightProps = $rightObj.PSObject.Properties.Name
        $allProps = $leftProps + $rightProps | Sort | Select -Unique
    
        $props = @()
    
        foreach ($propName in $allProps) {
    
            # test if has prop
            $leftHasProp = $propName -in $leftProps
            $rightHasProp = $propName -in $rightProps
    
            # get value from object
            $leftVal = $leftObj.$propName
            $rightVal = $rightObj.$propName
    
            # create custom output - 
            $prop = [pscustomobject] @{   
                Match = $(If ($propName -eq "SamAccountName" ) {"1st"} Else {
                            $(If ($leftHasProp -and !$rightHasProp ) {"Left"} Else {
                                $(If ($rightHasProp -and !$leftHasProp ) {"Right"} Else {
                                    $(If ($leftVal -eq $rightVal ) {"Same"} Else {"Diff"})
                                })
                              })
                         })
                PropName = $propName
                LeftVal = $leftVal
                RightVal = $rightVal
            }
    
            $props += $prop
        }
    
        # sort & format table widths
        $props | Sort-Object Match, PropName | Format-Table -Property `
                   @{ Expression={$_.Match}; Label="Match"; Width=6}, 
                   @{ Expression={$_.PropName}; Label="Property Name"; Width=25}, 
                   @{ Expression={$_.LeftVal }; Label="Left Value";    Width=40}, 
                   @{ Expression={$_.RightVal}; Label="Right Value";   Width=40}
    
    }
    

    然后像这样使用:

    $adUser1 = Get-ADUser 'Grace.Hopper' -Properties *
    $adUser2 = Get-ADUser 'Katherine.Johnson' -Properties *   
    Compare-ObjectProperties $adUser1 $adUser2
    

    几个有趣的笔记:

    【讨论】:

      【解决方案4】:

      这是我使用的函数:

      function Test-ObjectEquality {
          param(
              [Parameter(Mandatory = $true)]
              $Object1,
              [Parameter(Mandatory = $true)]
              $Object2
          )
      
          return !(Compare-Object $Object1.PSObject.Properties $Object2.PSObject.Properties)
      }
      

      例子:

      PS C:\> $obj1 = [pscustomobject] @{ 'a' = '5'; 'b' = 7; };
      PS C:\> $obj2 = [pscustomobject] @{ 'a' = '5'; 'b' = 7; };
      PS C:\> Test-ObjectEquality $obj1 $obj2
      True
      PS C:\> $obj2 = [psobject] @{ 'a' = '5'; 'b' = 7; };
      PS C:\> Test-ObjectEquality $obj1 $obj2
      False
      PS C:\> $obj2 = New-Object -TypeName PSObject -Property @{ 'a' = '5'; 'b' = 7; };
      PS C:\> Test-ObjectEquality $obj1 $obj2
      True
      PS C:\> $obj2 = [pscustomobject] @{ 'c' = '6'; 'b' = 7; };
      PS C:\> Test-ObjectEquality $obj1 $obj2
      False
      PS C:\> $obj2 = [pscustomobject] @{ 'a' = '5'; 'b' = 8; };
      PS C:\> Test-ObjectEquality $obj1 $obj2
      False
      PS C:\> $obj2 = [pscustomobject] @{ 'a' = '5'; 'b' = 7; c = 8 };
      PS C:\> Test-ObjectEquality $obj1 $obj2
      False
      PS C:\> $obj2 = [pscustomobject] @{ 'a' = '5'; 'b' = '7'; };
      PS C:\> Test-ObjectEquality $obj1 $obj2
      False
      

      我当然相信这可能会遗漏一些东西;但是,如果您查看 Properties 中的内容,您可以看到对象上每个属性的比较:

      PS C:\> $obj1.PSObject.Properties | Select-Object -First 1
      
      
      MemberType      : NoteProperty
      IsSettable      : True
      IsGettable      : True
      Value           : 5
      TypeNameOfValue : System.String
      Name            : a
      IsInstance      : True
      

      我很少关心对象属性的MemberType、Name、TypeNameOfValue 或Value。

      另外,请注意,如果您确实需要,可以比较 .PSObject.Members 而不是 .PSObject.Properties。这将比较属性和方法,尽管您只是比较方法调用而不是方法定义。

      【讨论】:

        【解决方案5】:

        我写了一个检查精确相等性的函数:

         function Global:Test-IdenticalObjects
         {
            param(
                [Parameter(Mandatory=$true)]$Object1,
                [Parameter(Mandatory=$true)]$Object2,
                $SecondRun=$false
            )
        
            if(-not ($Object1 -is [PsCustomObject] -and $Object2 -is [PsCustomObject))
            {
                Write-Error "Objects must be PsCustomObjects"
                return
            }
        
            foreach($property1 in $Object1.PsObject.Properties)
            {
                $prop1_name = $property1.Name
                $prop1_value = $Object1.$prop1_name
                $found_property = $false
                foreach($property2 in $Object2.PsObject.Properties)
                {
                    $prop2_name = $property2.Name
                    $prop2_value = $Object2.$prop2_name
                    if($prop1_name -eq $prop2_name)
                    {
                        $found_property = $true
                        if($prop1_value -ne $prop2_value)
                        {
                            return $false
                        }
                    }
                } # j loop
                if(-not $found_property) { return $false }
            } # i loop
            if($SecondRun)
            {
                return $true
            } else {
                Test-IdenticalObjects -Object1 $Object2 -Object2 $Object1 -SecondRun $true
            }
         } # function
        

        【讨论】:

        • 1) 不推荐 global: 范围 ID。 2) 大量不必要的工作和开销;一个Compare-Object 就可以了(见我的回答)。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        • 2013-07-15
        • 2011-03-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多