Powershell并排对象

时间:2016-05-07 14:33:03

标签: powershell object

继承我所拥有的,

两个对象:

 $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

现在,当我向用户展示时,它会显示在彼此之下。

我想让它们并排呈现:

Object1:      Object2:
Name1         Name3
Name2         Name4

我还有一个对象,但目前只有2.可以有人帮我吗?

如果$variables没有意义,我会更换它们以保持简单..

1 个答案:

答案 0 :(得分:4)

我做了类似的事情,我将两个对象并排比较以便于参考,我使用以下函数:

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
  }
}

您可以使用以下设计的示例对此进行测试:

$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

这将导致:

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

增加并排比较的对象数量,或者甚至以函数接受作为并排表格打印的对象数组的方式编写它并不困难