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

Variable number of fields to output in Select-Object cmdlet

假设我有一个包含描述多个实体的数据的 Obj。 我想像这样输出它(CSV,HTML,格式-Table,随便什么):

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即可。

与任何接受 array 对象的 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

以上结果:

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