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

I have two PowerShell functions, the first of which calls the second. They both take N arguments, and one of them is determined simply by adding a flag and calling the other. The following are examples:

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

Usage will look something like this:

 inner foo bar baz 

or

 outer wibble wobble wubble 

The goal is for the last example to be equivalent

 inner --flag wibble wobble wubble 

Problem: As defined here, the latter actually leads to two arguments passed to inner : the first is "-flag" and the second is an array containing "wibble", "wobble" and "wubble". I want inner get four arguments: a flag and three source arguments.

So I'm wondering how to convince powershell to expand the $ args array before passing it to inner , passing it as N elements, not just one array. I believe that you can do this in Ruby using the splatting operator (* character), and I'm sure PowerShell can do this, but I don’t remember how.

+6
arrays powershell
source share
3 answers

There is no good solution to this problem in PowerSHell V1. In V2, we added splatting (although 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: $ xy: $ yz: $ z"}

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

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

x: 1 2 3 y: z:

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

x: 1 y: 2 z: 3

+11
source share

Well, there may be a better way, but see if this works:

 inner --flag [string]::Join(" ", $args) 
0
source share

Based on the @EBGreen idea and related question that I noticed in the sidebar, you can find the following solution:

 function outer { invoke-expression "inner --flag $($args -join ' ')" } 

Note. This example uses the new Powershell 2.0 CTP CTP statement.

However, I would still like to find a better method, as it seems to be hacked and terribly safe.

0
source share

All Articles