How do you pass some data from parameter to an Array of Hashtable?
filnemane.ps1 -param @{ a = 1, b = 2, c =3}, @{ a = 4, b = 5, c =6}
to this output:
$param = @(
@{
a=1,
b=2,
c=3
},
@{
a=4,
b=5,
c=6
}
)
Thanks.
You declare a parameter to be of type [hashtable[]]
(that is, an array of [hashtable]
's):
# filename.ps1
param(
[hashtable[]]$Hashtables
)
Write-Host "Hashtables: @("
foreach($hashtable in $Hashtables){
Write-Host " @{"
foreach($entry in $hashtable.GetEnumerator()){
Write-Host " " $entry.Key = $entry.Value
}
Write-Host " }"
}
Write-Host ")"
With you're sample input you'd get something like:
PS C:\> .\filename.ps1 -Hashtables @{ a = 1; b = 2; c =3},@{ a = 4; b = 5; c =6}
Hashtables: @(
@{
c = 3
b = 2
a = 1
}
@{
c = 6
b = 5
a = 4
}
)
Notice that the output won't necessarily retain the key order from the input, because, well, that's not how hash tables work :)
As Matthew helpfully points out, if maintaining the key order is important, go with an ordered dictionary instead ([ordered]@{}
).
To support accepting either kind without messing up the key order, declare the parameter type as an array of [System.Collections.IDictionary]
- an interface that both types implement:
param(
[System.Collections.IDictionary[]]$Hashtables
)
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