Assuming:
$columnArray = @(
@{Name='COL_A';Type=[int];Measurements=@()},
@{Name='COL_B';Type=[string];Measurements=@()},
@{Name='COL_C';Type=[datetime];Measurements=@()}
)
Using the Where-Object
command to get COL_B
's Measurements
array:
($Fields | ? { $_.Name -eq 'COL_B' }).Measurements
Is there a more-succinct way of doing this? Would a nested set of PSCustomObject
s be a better approach?
You could modify the array itself with a method to do the finding:
Add-Member -InputObject $columnArray -MemberType ScriptMethod -Name FindCol -Value { param([String]$Column) $this | ? { $_.Name -eq $Column } }
Then you can do:
$columnArray.FindCol('COL_B').Measurements
Or you can do:
Add-Member -InputObject $columnArray -MemberType ScriptMethod -Name GetMeasurements -Value { param([String]$Column) $this | ? { $_.Name -eq $Column } | Select-Object -ExpandProperty Measurements }
Then:
$columnArray.GetMeasurements('COL_B')
If you are interested in looking element by key, than Hashtable
will be better approach than array.
$columnHashtable=@{
COL_A=@{Type=[int];Measurements=@()}
COL_B=@{Type=[string];Measurements=@()}
COL_C=@{Type=[datetime];Measurements=@()}
}
With Hashtable
you can get Measurements
array of COL_B
by this command:
$columnHashtable.COL_B.Measurements
And If you want to enumerate all elements in Hashtable
, then you can use following command:
$columnHashtable.GetEnumerator()|ForEach-Object ...
In case if order of elements in hash table matters, you could use [ordered]
operator before hash table literal to create OrderedDictionary
instead of Hashtable
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With