Consider this array of hash tables (edited to feature fixes from @mclayton):
$some_keys= @(
@{
foo="one";
bar="some other stuff";
},
# (...more entries...)
@{
foo="two";
bar="some more stuf";
}
)
Also, consider the following function:
function Get-WithKeys($foo, $bar){
# do stuff with $foo, $bar
}
Does Powershell provide any idiomatic way to pipe some_keys so that Get-WithKeys is called once per array element with the hashmap’s keys passed as function parameters?
For illustration purposes, I’m wondering if Powershell offers something for this effect:
$some_keys | <magic step> | Get-WithKeys
>Solution :
It’s called "splatting" – see about_Splatting.
Basically, you call the function with a hashtable variable as a parameter, but prefix it with @ instead of $ and each key in the hashtable is treated as a named parameter.
A simple example:
$my_hashtable = @{
foo="one";
bar="some other stuff"
}
# equivalent to Get-WithKeys -foo "one" -bar "some other stuff"
Get-WithKeys @my_hashtable
In your original sample you could do this to call Get-WithKeys once per item in your $some_keys array:
$some_keys | foreach-object { Get-WithKeys @_ }
Where @_ is using the automatic variable $_ as the value to splat.
Update
Note that your original code sample is defining an array of script blocks, not an array of hashtables. You need to prefix the { } with @ for a hashtable:
$some_keys= @(
@{
# ^^ - "@{" for a hashtable, "{" for a script block
foo="one";
bar="some other stuff"
},
# (...more entries...)
@{
foo="two";
bar="some more stuf"
}
)