PowerShell - How to tell if two objects are identical

后端 未结 5 1514
一个人的身影
一个人的身影 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:27

    You can compare two PSObject objects for equality of properties and values by using Compare-Object to compare the Properties properties of both PSObjectobjects. Example:

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

    If you want it in a function:

    function Test-PSCustomObjectEquality {
      param(
        [Parameter(Mandatory = $true)]
        [PSCustomObject] $firstObject,
    
        [Parameter(Mandatory = $true)]
        [PSCustomObject] $secondObject
      )
      -not (Compare-Object $firstObject.PSObject.Properties $secondObject.PSObject.Properties)
    }
    

提交回复
热议问题