PowerShell - 如何判断两个对象是否相同

时间:2017-11-30 15:04:50

标签: powershell object if-statement conditional equality

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

你如何测试平等?

示例

$obj1& $obj2相同

enter image description here

这是我尝试过的:

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"

修改

相同

enter image description here

5 个答案:

答案 0 :(得分:3)

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

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)
}

答案 1 :(得分:1)

我建议使用Deleted: m SetHash(a b c k n) 执行此任务:

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
    }
}

答案 2 :(得分:0)

这是我使用的功能:

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

我经常关注的不仅仅是对象的MemberTypeNameTypeNameOfValueValue&#39 ; s属性。

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

答案 3 :(得分:0)

如果您想一次测试每个对象属性的相等性,以便比较和对比两个对象并查看哪些不同,则可以使用以下功能,该功能改编自本文:如何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 :(得分:-1)

我编写了一个检查完全相等的函数:

 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