Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 218
Charlie Avatar asked Jan 15 '09 23:01

Charlie


1 Answers

There isn't a good solution to this problem in PowerSHell V1. In V2 we added splatting (though for various reasons, we use @ instead of * for this purpose). Here's what it looks like:

PS (STA-ISS) (2) > function foo ($x,$y,$z) { "x:$x y:$y z:$z" }

PS (STA-ISS) (3) > $a = 1,2,3

PS (STA-ISS) (4) > foo $a # passed as single arg

x:1 2 3 y: z:

PS (STA-ISS) (5) > foo @a # splatted

x:1 y:2 z:3

like image 176
Bruce Payette Avatar answered Sep 23 '22 21:09

Bruce Payette