arrayspowershell

How to expand a PowerShell array when passing it to a function


I have two PowerShell functions, the first of which invokes the second. They both take N arguments, and one of them is defined to simply add a flag and invoke the other. Here are example definitions:

function inner
{
  foreach( $arg in $args )
    {
      # do some stuff
    }
}

function outer
{
  inner --flag $args
}

Usage would look something like this:

inner foo bar baz

or this

outer wibble wobble wubble

The goal is for the latter example to be equivalent to

inner --flag wibble wobble wubble

The Problem: As defined here, the latter actually results in two arguments being passed to inner: the first is "--flag", and the second is an array containing "wibble", "wobble", and "wubble". What I want is for inner to receive four arguments: the flag and the three original arguments.

So what I'm wondering is how to convince powershell to expand the $args array before passing it to inner, passing it as N elements rather than a single array. I believe you can do this in Ruby with the splatting operator (the * character), and I'm pretty sure PowerShell can do it, but I don't recall how.


Solution

  • There isn't a good solution to this problem in PowerShell Version 1. In Version 2 we added splatting (though for various reasons, we use @ instead of * for this purpose).

    Here's what it looks like:

    PS> function foo ($x,$y,$z) { "x:$x y:$y z:$z" }
    PS> $a = 1,2,3
    PS> foo $a # passed as single arg
    x:1 2 3 y: z:
    PS> foo @a # splatted
    x:1 y:2 z:3