4

I have a script internal.ps1 which accepts certain params:

param ($paramA, $paramB)
Write-Host $PSBoundParameters

And a script caller.ps1 that calls it:

.\internal -paramA A -paramB B

It works great:

PS C:\temp> .\caller
[paramA, A] [paramB, B]    <<<< bounded to both params

However, in caller I want to keep the parameters to internal in a var, and use it later. However, that doesn't work:

$parms = "-paramA A -paramB B"
# Later...
.\internal $parms

Result: [paramA, A -paramB B]   <<<<< All got bounded to ParamA

Neither does using an array:

$parms = @("A", "B")
# Later...
.\internal $parms

Result: [paramA, System.Object[]]  <<<< Again, all bound to ParamA

How can I accomplish this? Note that the actual commandline is more complex, and may have unknown length.

3 Answers 3

5

The splatting operator (@) should do what you need. Consider first this simple function:

function foo($a, $b) { "===> $a + $b" }

Calling with explicit arguments yields what you would expect:

foo "hello" "world"
===> hello + world

Now put those two values in an array; passing the normal array yields incorrect results, as you have observed:

$myParams = "hello", "world"
foo $myParams
===> hello world +

But splat the array instead and you get the desired result:

foo @myParams
===> hello + world

This works for scripts as well as for functions. Going back to your script, here is the result:

 .\internal @myParams
[paramA, hello] [paramB, world]

Finally, this will work for an arbitrary number of parameters, so know a priori knowledge of them is needed.

0
0

powershell -file c:\temp\test.ps1 @("A","B")

or

powershell -command "c:\temp\test.ps1" A,B

0

Your script expects 2 arguments, but your previous attempts pass just a single one (a string and an array respectively). Do it like this:

$parms = "A", "B"
#...
.\internal.ps1 $parm[0] $parm[1]
1
  • Ok, but how would I use that when I don't know the length of the params? And can I have the $parms var somehow express the binding of paramA to A, etc. (see edited question for usage)?
    – Jonathan
    Commented Jun 19, 2013 at 14:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.