Powershell command line parameters and '--'

2019-02-22 23:52发布

问题:

For whatever reason, when I try to call a C# program I'm writing, and I try to pass two arguments with '--' in the command line, Powershell doesn't call the program with my command line.

For instance, I'm providing the command line:

.\abc.exe foo.txt -- bar --

When I call this, the C# program's main only gets the command line args:

foo.txt bar --

instead of

foo.txt -- bar --

as would be expected.

Anybody know why this would be happening?

BTW, if I call it as:

.\abc.exe foo.txt '--' bar '--'

it works as expected.

Also, calling it as:

& .\abc.exe foo.txt -- bar --

Doesn't seem to help.

My reason for thinking this is a powershell weirdness is that if I run the same command line from CMD.EXE everything works as expected.

回答1:

A double hyphen instructs PowerShell to treat everything coming after as literal arguments rather than options, so that you can pass for instance a literal -foo to your script/application/cmdlet.

Example:

PS C:\> echo "-bar" | select-string -bar
Select-String : A parameter cannot be found that matches parameter name 'bar'.
At line:1 char:28
+ "-bar" | select-string -bar <<<<
    + CategoryInfo          : InvalidArgument: (:) [Select-String], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SelectStringCommand

vs.

PS C:\> echo "-bar" | select-string -- -bar

-bar

To avoid this behavior you must either quote ("--", '--') or escape (`--) the double hyphen.



回答2:

With PowerShell 3 you can use --% to stop the normal parsing powershell does.

.\abc.exe --% foo.txt -- bar --


回答3:

wow. sometimes I really hate powershell. It seems that the interpreter is thinking '--' is the decrement operator or something. If I put the escape character before the -- parameters, i.e. use the command line:

.\abc.exe foo.txt `-- bar `--

all is well.

As I said, sometimes I really hate powershell. Hopefully this helps someone else with this problem.