0

I am unable to understand Parameter passing behavior in Powershell.

Say, I have a script callScript.ps1

param($a="DefaultA",$b="DefaultB")
echo $a, $b

Say, another script calls callScript.ps1.

.\callScript.ps1
# outputs DefaultA followed by DefaultB as expected
.\callScript.ps1 -a 2 -b 3
# outputs 2 followed by 3 as expected
$arguments='-a 2 -b 3'
callScript.ps1 $arguments
# I expected output as previous statement but it is as follows.
# -a 2 -b 3
# DefaultB

How can I run a powershell script by constructing command dynamically as above? Can you please explain why the script the $arguments is interpreted as $a variable in callScript.ps1?

1
  • You are passing a single string to you script which is expecting 2 parameters. Therefore it's fallbacking to DefaultB (which is missing). I think you should consider refactoring your function to accept an array instead. At least if you really need to pass parameters as a single argument. Commented Oct 17, 2017 at 15:02

2 Answers 2

1

what's happening here is that you're passing a string:

'-a 2 -b 3' as the parameter for $a

you need to specify the values within the param, if you really needed to do it as you have above (there's definitely a better way though) you could do this using Invoke-Expression (short iex)

function doprint {
    param( $a,$b )
    $a ; $b
}

$arg = '-a "yes" -b "no"'

"doprint $arg" | iex

you could also change your function to take in an array of values like this:

function doprint {
    param( [string[]]$a )
    $a[0] ; $a[1]
}

$arg = @('yes','no')

doprint $arg
Sign up to request clarification or add additional context in comments.

Comments

1

As has already been hinted at, you can't pass a single string as your script is expecting two params - the string is taken as input for param $a, whilst param $b takes the default value.

You can however build a simple hash table containing your arguments, and then use splatting to pass them to the script.

The changes to your code are minimal:

$arguments=@{a="2";b="3"}

callScript.ps1 @arguments

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.