Skip to content

Instantly share code, notes, and snippets.

@Sarafian
Created September 2, 2016 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sarafian/92fb1596b28838c40a17954562d15300 to your computer and use it in GitHub Desktop.
Save Sarafian/92fb1596b28838c40a17954562d15300 to your computer and use it in GitHub Desktop.
A cmdlet to format the output of PowerShell's Compare-Object cmdlet.
<#
.Synopsis
Formats the output of Compare-Object for even results
.DESCRIPTION
When the compared set has even entries use this commandlet to promote the output Compare-Object to Name,Original,Changed using the SideIndicator
.PARAMETER Compare
The output of Compare-Object
.PARAMETER PathAsName
The path to use to create the Name column in the output
.EXAMPLE
Compare-Object -ReferenceObject $original -DifferenceObject $changed |Format-Compare -PathAsName "Node.Name"
.EXAMPLE
Compare-Object -ReferenceObject $original -DifferenceObject $changed |Format-Compare
.INPUTS
The output of Compare-Object
.NOTES
Not sure if the functionality can be extended for a non-even compared sets. Looking for ideas.
.LINK
Compare-Object
#>
function Format-Compare
{
[CmdletBinding(DefaultParameterSetName='Parameter Set 1')]
Param
(
# Param1 help description
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[PSObject[]]$Compare,
[Parameter(Mandatory=$false)]
[string]$PathAsName
)
Begin
{
$right=@()
$left=@()
}
Process
{
#Extract all the records that are changed in the DifferenceObject parameter of Compare-Object
$right+=$Compare|Where-Object -Property SideIndicator -EQ "=>"
#Extract all the records that are changed in the ReferenceObject parameter of Compare-Object
$left+=$Compare|Where-Object -Property SideIndicator -EQ "<="
}
End
{
if($left.Count -ne $right.Count){
throw "Can't format object with uneven =>/<= result"
}
$output=@()
for($i=0;$i -lt $left.Count;$i++)
{
$hash=@{
Original=$left[$i].InputObject
Changed=$right[$i].InputObject
}
if($PathAsName)
{
$hash.Name=Invoke-Expression "`$left[$i].InputObject.$PathAsName"
$output+=New-Object -TypeName PSObject -Property $hash |Select-Object Name,Original,Changed
}
else
{
$output+=New-Object -TypeName PSObject -Property $hash |Select-Object Original,Changed
}
}
$output
}
}
@Sarafian
Copy link
Author

Sarafian commented Sep 2, 2016

Currently this gist works only for even compare result sets of Compare-Object. That means that the reference (-ReferenceObject) and difference (-DifferenceObject) objects have only changes to identical values. For example compare xml fragments that have only changes and not added or removed nodes.

I think there is more potential here but I'm looking for ideas also.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment