gpt4 book ai didi

PowerShell 对象多行不同的属性

转载 作者:行者123 更新时间:2023-12-03 01:30:13 29 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Not all properties displayed

(1 个回答)


2年前关闭。



$vms = @()

$foo = New-Object -TypeName PSObject
$foo | Add-Member -MemberType NoteProperty -Name "Name" -Value "Host1"
$foo | Add-Member -MemberType NoteProperty -Name "OSDisk" -Value "64 GB"
$vms += $foo

$bar = New-Object -TypeName PSObject
$bar | Add-Member -MemberType NoteProperty -Name "Name" -Value "Host2"
$bar | Add-Member -MemberType NoteProperty -Name "OSDisk" -Value "64 GB"
$bar | Add-Member -MemberType NoteProperty -Name "DataDisk1" -Value "128 GB"
$vms += $BAR

$vms[0] | ft
$vms[1] | ft
$vms | ft

如您所见,第二行的属性比第一行多。
显示时,我只得到第一行中存在的属性,其他属性被忽略。

PS C:> $vms[0] |英尺
Name  OSDisk
---- ------
Host1 64 GB

PS C:> $vms[1] |英尺
Name  OSDisk DataDisk1
---- ------ ---------
Host2 64 GB 128 GB

PS C:> $vms |英尺
Name  OSDisk
---- ------
Host1 64 GB
Host2 64 GB

我希望实现的是在每一行中拥有每个属性:
Name  OSDisk  DataDisk1
---- ------ ----------
Host1 64 GB
Host2 64 GB 128 GB

[编辑]
属性可能会有所不同,在我的情况下,VM 可能有一个或多个数据磁盘。

最佳答案

前段时间我做了一个辅助函数来完成对象数组中的第一项,并找到所有标题:

function Complete-ObjectHeaders {
# function to add properties to the first item in a collection of PSObjects
# when this object is missing properties from items further down the array.
# you may need this is you have such a collection and want to export it
# to Csv, since Export-Csv only looks at the first item to create the
# csv column headers.
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
[PSObject[]]$Collection,

[int]$MaxItemsToTest = -1, # < 0 --> test all items in the collection
[switch]$SortHeaders
)

# Try and find all headers by looping over the items in the collection.
# The headers will be captured in the order in which they are found.
if ($MaxItemsToTest -gt 0) {
$MaxItemsToTest = [math]::Min($MaxItemsToTest, $Collection.Count)
$headers = for($i = 0; $i -lt $MaxItemsToTest; $i++) {
($Collection[$i].PSObject.Properties).Name
}
$headers = $headers | Select-Object -Unique
}
else {
$headers = $Collection | ForEach-Object {($_.PSObject.Properties).Name} | Select-Object -Unique
}

if ($SortHeaders) { $headers = $headers | Sort-Object }

# update the first object in the collection to contain all headers
$Collection[0] = $Collection[0] | Select-Object $headers

,$Collection
}

在你的情况下,你可以这样做
Complete-ObjectHeaders -Collection $vms | Format-Table -AutoSize

输出

Name  OSDisk DataDisk1
---- ------ ---------
Host1 64 GB
Host2 64 GB 128 GB


希望有帮助

关于PowerShell 对象多行不同的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58915163/

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