Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using --% in PowerShell

Tags:

powershell

I've seen --% referenced in relation to executing a command with multiple parameters. I'm having trouble googling for more information about it. I suspect Google thinks I'm trying a special syntax. I'm hoping to be able to execute the plink command from PowerShell and using variables to add the parameters like this:

&"./plink.exe" --% $Hostname -l $Username -pw $Password $Command

It works if I specify the information, but not with variable substitution.

like image 503
Brian Wochele Avatar asked Sep 20 '13 18:09

Brian Wochele


2 Answers

I had this same problem, and there is a workaround for this problem. I recently blogged about this (Use PowerShell variables after escaping parsing in PowerShell v3.0 - 2013-09-17) after taking inspiration from my own answer, Executing external command from PowerShell is not accepting a parameter.

The trick is to use --% itself as a variable and include that along with other variables in PowerShell.

So instead of this,

&"./plink.exe" --% $Hostname -l $Username -pw $Password $Command

try this:

$escapeparser = '--%'
& "./plink.exe" $escapeparser $Hostname -l $Username -pw $Password $Command

It may be related, but I used single quotes in all variables.

like image 132
Mitul Avatar answered Oct 13 '22 08:10

Mitul


I also blogged about this shortly after v3 shipped. --% turns PowerShell into a dumb parser from that character sequence until the end of the line. That means you don't get any variable evaluation after --%.. However, you case use environment variables like so:

$env:hostname = $hostname
$env:user     = $user
$env:passwd   = $password
$env:command  = $command
.\plink.exe --% %hostname% -l %user% -pw %passwd% %Command%

That said, in this scenario I don't see any reason to use --%. This should work just fine:

.\plink.exe $Hostname -l $Username -pw $Password $Command

You only want to use --% when the EXE's command line arguments expect arguments with characters that trip up PowerShell e.g.:

tf.exe status . /r /workspace:*;domain\user

In this case, tf.exe uses ; to separate the workspace name from the workspace owner but PowerShell interprets the ; as a statement separator which messes up the invocation of tf.exe. You would fix it like so:

tf.exe status . /r --% /workspace:*;domain\user

BTW the use of & is unnecessary here because you don't need to quote `.\plink.exe'. You would only need to quote it if the filename or path contained a space.

like image 31
Keith Hill Avatar answered Oct 13 '22 06:10

Keith Hill