2

假设我有一个带有描述多个实体的数据的 Obj。我想像这样输出它(CSV、HTML、Format-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

4

1 回答 1

3

| % {Select-Object

不要使用%ForEach-Objectcmdlet)通过管道传递到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

以上产生:

Property Code  : pc
Property Desc. : descr
Entity1        : e1
Entity2        : e2
Entity3        : e3
Entity4        : e4
Entity5        : e5
于 2020-06-11T22:38:54.937 回答