假设我有一个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
不要使用%
(ForEach-Object
cmdlet)通过管道传输到Select-Object
-直接通过管道传输到Select-Object
。
@{Label = "Entity1"; Expression = {$_.entity1}}
除非您需要更改标签(属性)名称的case,只需将entity1
传递给Select-Object
。
与接受对象[[array的任何cmdlet参数一样,您可以随意使用数组文字或先前构造的数组传递数组:
# Properties that need renaming.
$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'
$ObjData | Select-Object $propDefs # add Format-Table, if needed, for display formatting