PowerShell - How to tell if two objects are identical

后端 未结 5 1511
一个人的身影
一个人的身影 2021-01-24 17:05

Let\'s say you have two objects that are identical (meaning they have the same properties and the same values respectively).

How do you test for equality?

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-24 17:13

    I'd suggest using Compare-Object for this task:

    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
    

提交回复
热议问题