gpt4 book ai didi

powershell - 在Select-Object cmdlet中输出的可变字段数

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

假设我有一个Obj,其中的数据描述了多个实体。
我想这样输出(CSV,HTML,格式表等):

Property Code   Property descr.  Entity1  Entity2  Entity3
abs_de234 abs prop for de 132 412 412
abs_fe234 abs prop for fe 423 432 234
... ... ... ... ...

我会用类似的东西:
$ObjData | % {Select-Object @{Label = "Property Code"; Expression = {$_.propcode}}, @{Label = "Property Desc."; Expression = {$_.descr}},  @{Label = "Entity1"; Expression = {$_.entity1}}, @{Label = "Entity2"; Expression = {$_.entity2}},@{Label = "Entity3"; Expression = {$_.entity3}} }| Format-Table

但是,如果我的对象具有可变数量的实体怎么办?假设这些属性都在一个数组中:
$EntityList = @('Entity1', 'Entity2', 'Entity4', 'Entity5', 'Entity5')

如何基于 $EntityList构造相应的 Select-Object命令?

更新:基于 Select-Object的帮助:
Select-Object
[-InputObject <PSObject>]
[[-Property] <Object[]>]
[-ExcludeProperty <String[]>]
[-ExpandProperty <String>]
[-Unique]
[-Last <Int32>]
[-First <Int32>]
[-Skip <Int32>]
[-Wait]
[<CommonParameters>]

这是否意味着我应该可以只使用 Select-Object -Property $EntityList

最佳答案

| % {Select-Object



不要使用 %( ForEach-Object cmdlet)通过管道传输到 Select-Object,而不是通过管道直接传输到 Select-Object

@{Label = "Entity1"; Expression = {$_.entity1}}



除非您需要更改标签(属性)名称的大小写,否则只需将 entity1传递给 Select-Object即可。

与任何接受对象数组的cmdlet参数一样,您可以随意将数组作为数组文字(通过 ,逐一枚举元素)或作为通过变量传递的先前构造的数组传递:
# Properties that need renaming.
# Note: Unless you need to *transform* the input property value,
# you don't strictly need a *script block* ({ ... }) and can use
# a *string* with the property name instead.
# E.g., instead of {$_.propcode} you can use 'propcode'
$propDefs =
@{Label = "Property Code"; Expression = {$_.propcode}},
@{Label = "Property Desc."; Expression = {$_.descr}}

# Add properties that can be extracted as-is:
$propDefs += 'Entity1', 'Entity2', 'Entity4', 'Entity5', 'Entity5'

# Note: Passing the array *positionally* implies binding to the -Property parameter.
$ObjData | Select-Object $propDefs # add Format-Table, if needed, for display formatting

展示:
# Sample input object
$ObjData = [pscustomobject] @{
propcode = 'pc'
descr = 'descr'
Entity1 = 'e1'
Entity2 = 'e2'
Entity3 = 'e3'
Entity4 = 'e4'
Entity5 = 'e5'
}

$propDefs =
@{Label = "Property Code"; Expression = {$_.propcode}},
@{Label = "Property Desc."; Expression = {$_.descr}}

$propDefs += 'Entity1', 'Entity2', 'Entity3', 'Entity4', 'Entity5'

$ObjData | Select-Object $propDefs

以上 yield :

Property Code  : pc
Property Desc. : descr
Entity1 : e1
Entity2 : e2
Entity3 : e3
Entity4 : e4
Entity5 : e5

关于powershell - 在Select-Object cmdlet中输出的可变字段数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62334577/

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