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-Object) を使用して to パイプをSelect-Object使用しないでください。Select-Object

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

ラベル (プロパティ) 名の大文字と小文字を変更する必要がない限り、単に に渡しentity1ますSelect-Object

オブジェクトの配列を受け入れる任意のコマンドレット パラメーターと同様に、配列を配列リテラル (要素を 1 つずつ列挙,) として、または変数を介して渡される以前に作成された配列として自由に渡すことができます。

# 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 に答える