1

I am using a PowerShell session to run some commands and want the argument to be passed as is, including quotes like ". The command I'm passing does not include the quotes, here is the code:

$myarg= "run"
$CArg = "XXX"    ## CArg should be passed as "XXX"

Invoke-Command -Session $session  -Scriptblock { param($myarg,$CArg) &'C:\program.exe'  $myarg  -CArg $CArg -ArgumentList $myarg,$CArg

I also tried @ArgumentList and had the same issue

4 Answers 4

1

For problems like this I usually fall back to using [scriptblock]::create(), and an expandable here-string:

$myarg= "run"
$CArg = "XXX"    ## CArg should be passed as "XXX"

$scriptblock = [scriptblock]::create(@"
&'C:\program.exe'  $myarg  -CArg "$CArg"
"@)

 Invoke-Command -Session $session  -Scriptblock $scriptblock

The here string lets you put whatever kind of quotes you want, whereever you want them.

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

3 Comments

Can you clarify that?
I added my solution below, for some reason powershell does not like @ at the beginning of the script, i used to do it in C# to escape \ characters. in C#: File.Open(@"C:\program.exe") // this is equivalant to : File.Open("C:\\program.exe") // these are the same for powershell this does not work...
I'm not sure what you mean by "@ is not acceptable in PS", but I suspect you many not be formatting the here-string correctly. In a here-string, the opening @" can be in any position on the line, but the closing "@ must start in position 1.
1

If you want the receiving EXE to get the parameter with quotes surrounding it, you have to work at it a bit to defeat the various phases that strip away quotes. Try this:

120> $carg = "`"`"`"foo`"`"`""
121> Invoke-Command { param($myarg,$CArg) echoargs $myarg -CArg $CArg } -ArgumentList myarg,$CArg

Arg 0 is <run>
Arg 1 is <-CArg>
Arg 2 is <"foo">

Command line:
"C:\Program Files (x86)\PowerShell Community Extensions\Pscx3\Pscx\Apps\EchoArgs.exe"  run -CArg """foo"""

Note that echoargs is a utility from PSCX that helps with debugging parameter passing to native exes.

Comments

0

I am not sure what you want to achieve but if you pass argument as """XXX"""

PS C:\Users\demo.b> """XXXX"""
"XXXX"

Comments

0
$CArg = "`"XXX`""
$string = "&'C:\program.exe' $myarg -CArg" +  "$CArg"
$scriptblock = [scriptblock]::create($string)
Invoke-Command -Session $session -Scriptblock $scriptblock

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.