2

I intend to use a powershell variable in a script to pass a string value to a command whereupon the command is executed with the parameters as defined in the string. I have been looking at this for a couple of hours now and I don't see what I am doing wrong. I have simplified as much as I can. In the hope of fresh eyes I attach an image, showing:

a. the script that I am using. It's three lines long.

$Parms = "-it amazonlinux2 /bin/sh"
Write-Output "& docker run $Parms"
& docker run $Parms

b. the PS command line where I execute the script.

PS C:\dev\gamelift\serversdk\build> ./test

c. the result of the script's execution

& docker run -it amazonlinux2 /bin/sh
unknown shorthand flag: ' ' in - amazonlinux2 /bin/sh
See 'docker run --help'.

d. the same command executed immediately at the prompt.

PS C:\dev\gamelift\serversdk\build> docker run -it amazonlinux2 /bin/sh

e. the result of the prompt command, which is correct

sh-4.2#

Image of the above

What magic is happening so that the Write-Output is not being interpreted as the command? I have tried:

a. docker run $Parms (without the &)

b. & docker run "$Parms" (in quotes)

c. $Parms = "amazonlinux2 /bin/sh" and & docker run -it $Parms (different error)

d. $Parms = "amazonlinux2" and & docker run -it $Parms /bin/sh (works)

e. escaping the hyphen (different error)

f. $Parms = "-it amazonlinux2 /bin/sh" and each of & docker run $($Parms), & docker run ${$Parms} and & docker run ${Parms}

I'm feeling a bit stupid. I can't see how the Write-Output is right but the call command is bork. It can't be that hard...

0

2 Answers 2

2

The Call operator (&) does not parse strings so "you cannot use command parameters within a string when you use the call operator". You can, however, pass an array so the following will work:

$Parms = "-it amazonlinux2 /bin/sh"
Write-Output "& docker run $Parms"
$myargs = -split $Parms 
& docker run $myargs

Alternatively using Invoke-Expression (alias iex) will also do the trick e.g.:

$Parms = "-it amazonlinux2/bin/sh"
Write-Output "& docker run $Parms"
iex "docker run $Parms"
Sign up to request clarification or add additional context in comments.

Comments

1

This is a frequently asked question, although not well documented. The call operator parameters work as an array:

$Parms = '-it','amazonlinux2','/bin/sh'
Write-Output "& docker run $Parms"
& docker run $Parms

I would just run docker directly.

docker -it amazonlinux2 /bin/sh

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.