Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
    }
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading