Created
September 28, 2023 01:05
-
-
Save Wind010/4e1d09cce378cd100e5f27d9487c5cee to your computer and use it in GitHub Desktop.
Powershell function to compare property values of two PSObjects that contain only primitive type properties (non-nested).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Function to compare property values of two PSObjects with wrapper around Compare-Object. | |
| # Usage Compare-Objects <reference_object> <diff_object> <array_of_relevant_properties> | |
| # The `strict` parameter is relevant if you want to compare integer to floating point number strictly. | |
| # The `explicit` parameter is default to $true to see value by value difference. | |
| function Compare-Objects { | |
| param ( | |
| [Parameter(Mandatory=$true)] | |
| [PSObject]$obj1, | |
| [Parameter(Mandatory=$true)] | |
| [PSObject]$obj2, | |
| [Parameter(Mandatory=$true)] | |
| [array]$properties, | |
| [Parameter(Mandatory=$false)] | |
| [bool]$strict=$true, | |
| [Parameter(Mandatory=$false)] | |
| [bool]$explicit=$true | |
| ) | |
| foreach ($property in $properties) { | |
| Write-Host "Comparing $property..." | |
| $p1 = $obj1.$property | |
| $p2 = $obj2.$property | |
| if ($p1.Length -ne $p2.Length) { | |
| Write-Host "Difference in length for $p1 and $p2" | |
| } | |
| if ($strict) { | |
| $p1 = $p1 | ForEach-Object {$_.ToString()} | |
| $p2 = $p2 | ForEach-Object {$_.ToString()} | |
| } | |
| if ($explicit) { | |
| for ($i = 0; $i -lt $p2.Length; $i++) { | |
| if ($p1[$i] -ne $p2[$i]) { | |
| $diff += "$($p1[$i]) != $($p2[$i]) `r`n" | |
| } | |
| } | |
| } | |
| else { | |
| $diff = Compare-Object $p1 $p2 | |
| } | |
| if ($diff) { | |
| Write-Host "Differences found:" | |
| $diff | |
| } | |
| else { | |
| Write-Host "No differences found comparing $property" | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment