Mike
Mike

Reputation: 199

Powershell Side by side objects

Heres what I have,

Two objects:

 $Global:Object1 = New-Object -TypeName PSObject
$Global:Object1 | Add-Member -MemberType NoteProperty -Name Name1 -Value $Name1.Name1
$Global:Object1 | Add-Member -MemberType NoteProperty -Name Name2 -Value $Name2.Name2

$Global:Object2 = New-Object -TypeName PSObject
$Global:Object2 | Add-Member -MemberType NoteProperty -Name Name3 -Value $Name3.Name3
$Global:Object2 | Add-Member -MemberType NoteProperty -Name Name4 -Value $Name4.Name4

Now when I present that to the user, it appears how underneath each other.

I would like to have them presented side by side:

Object1:      Object2:
Name1         Name3
Name2         Name4

I will have one more object, but at the moment only 2. Can anyone help me out please?

If the $variables don't make sense, I replaced them to keep things simple..

Upvotes: 3

Views: 2758

Answers (1)

Richard Slater
Richard Slater

Reputation: 6368

I do something similar in that I compare two objects side by side for easy reference, I use the following function:

function Compare-ObjectsSideBySide ($lhs, $rhs) {
  $lhsMembers = $lhs | Get-Member -MemberType NoteProperty, Property | Select-Object -ExpandProperty Name
  $rhsMembers = $rhs | Get-Member -MemberType NoteProperty, Property | Select-Object -ExpandProperty Name
  $combinedMembers = ($lhsMembers + $rhsMembers) | Sort-Object -Unique


  $combinedMembers | ForEach-Object {
    $properties = @{
      'Property' = $_;
    }

    if ($lhsMembers.Contains($_)) {
      $properties['Left'] = $lhs | Select-Object -ExpandProperty $_;
    }

    if ($rhsMembers.Contains($_)) {
      $properties['Right'] = $rhs | Select-Object -ExpandProperty $_;
    }

    New-Object PSObject -Property $properties
  }
}

You can test this out with the following, contrived, example:

$object1 = New-Object PSObject -Property @{
  'Forename' = 'Richard';
  'Surname' = 'Slater';
  'Company' = 'Amido';
  'SelfEmployed' = $true;
}

$object2 = New-Object PSObject -Property @{
  'Forename' = 'Jane';
  'Surname' = 'Smith';
  'Company' = 'Google';
  'MaidenName' = 'Jones'
}

Compare-ObjectsSideBySide $object1 $object2 | Format-Table Property, Left, Right

Which will result in:

Property     Left    Right
--------     ----    -----
Company      Amido   Google
Forename     Richard Jane
MaidenName           Jones
SelfEmployed True
Surname      Slater  Smith

It wouldn't be difficult to increase the number of objects being compared side-by-side, or even write it in such a way that the function accepts an array of objects which are printed as a side-by-side table.

Upvotes: 4

Related Questions