gpt4 book ai didi

Powershell 并排对象

转载 作者:行者123 更新时间:2023-12-01 12:28:23 25 4
gpt4 key购买 nike

这是我的,

两个对象:

 $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 没有意义,我会替换它们以使事情简单化..

最佳答案

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

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

增加并排比较对象的数量并不难,甚至可以将其编写为函数接受一个对象数组,这些对象被打印为并排表.

关于Powershell 并排对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37089766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com