简体   繁体   中英

Powershell command built dynamically — Parameter Passing Issue

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 ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM