Powershell命令行参数和' - '

Kel*_*y L 8 powershell command-line powershell-2.0

无论出于何种原因,当我尝试调用我正在编写的C#程序时,我尝试在命令行中使用' - '传递两个参数,Powershell不会使用我的命令行调用该程序.

例如,我正在提供命令行:

.\abc.exe foo.txt -- bar --
Run Code Online (Sandbox Code Playgroud)

当我调用它时,C#程序的main只获取命令行args:

foo.txt bar --
Run Code Online (Sandbox Code Playgroud)

代替

foo.txt -- bar --
Run Code Online (Sandbox Code Playgroud)

正如所料.

有人知道为什么会这样吗?

顺便说一句,如果我把它称为:

.\abc.exe foo.txt '--' bar '--'
Run Code Online (Sandbox Code Playgroud)

它按预期工作.

另外,将其称为:

& .\abc.exe foo.txt -- bar --
Run Code Online (Sandbox Code Playgroud)

似乎没有帮助.

我之所以认为这是一个PowerShell的怪异,如果我从CMD.EXE运行相同的命令行,一切都按预期工作.

Ans*_*ers 7

双连字符指示PowerShell将后面的所有内容视为文字参数而不是选项,以便您可以将文字-foo传递给脚本/ application/cmdlet.

例:

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
Run Code Online (Sandbox Code Playgroud)

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

-bar
Run Code Online (Sandbox Code Playgroud)

要避免此行为,您必须引用("--",'--')或转义(`--)双连字符.


Lar*_*ens 6

使用PowerShell 3,您可以使用 - %来停止PowerShell的正常解析.

.\abc.exe --% foo.txt -- bar --
Run Code Online (Sandbox Code Playgroud)