Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell command line parameters and '--'

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 arguments:

foo.txt bar --

instead of

foo.txt -- bar --

as would be expected.

Why would this 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.

like image 218
Kelly L Avatar asked Apr 03 '13 06:04

Kelly L


People also ask

What does the & symbol mean in PowerShell?

& is the call operator which allows you to execute a command, a script, or a function.

How do I pass multiple parameters to a PowerShell script?

To pass multiple parameters you must use the command line syntax that includes the names of the parameters. For example, here is a sample PowerShell script that runs the Get-Service function with two parameters. The parameters are the name of the service(s) and the name of the Computer.

What does %% mean in PowerShell?

% is an alias for the ForEach-Object cmdlet. An alias is just another name by which you can reference a cmdlet or function.

How do I run a PowerShell script from the command line with parameters?

To run scripts via the command prompt, you must first start up the PowerShell executable (powershell.exe), with the PowerShell location of C:\Program Files\WindowsPowerShell\powershell.exe and then pass the script path as a parameter to it.


2 Answers

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

.\abc.exe --% foo.txt -- bar --
like image 146
Lars Truijens Avatar answered Oct 10 '22 19:10

Lars Truijens


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.

like image 12
Ansgar Wiechers Avatar answered Oct 10 '22 18:10

Ansgar Wiechers