RAM
RAM

Reputation: 2759

Call powershell function with parameters piped from an array of hash tables

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

Upvotes: 0

Views: 376

Answers (1)

mclayton
mclayton

Reputation: 9975

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 variable to splat.

Upvotes: 2

Related Questions