2013-04-03 192 views
4

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

举例来说,我提供的命令行:

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

当我的话,这个C#程序的主只得到命令行参数:

foo.txt bar -- 

,而不是

foo.txt -- bar -- 

如预期的那样。

有人知道为什么会发生这种情况吗?

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

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

它按预期工作。

此外,称其为:

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

似乎并没有帮助。

我认为这是一个PowerShell奇怪的原因是,如果我从CMD.EXE运行相同的命令行一切都按预期工作。

+0

进一步说明。显然这两个' - '不是全部问题。看起来powershell dropbx是第一个' - ',即使第二个不在那里。看起来像 - 必须对PowerShell有特殊意义。 –

回答

4

双连字符指示PowerShell将后来的所有内容视为文字参数而不是选项,以便您可以将字面值-foo传递给脚本/应用程序/ 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 

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

-bar 

为了避免这种情况,你必须要么引用("--"'--')或逃生(`--)与双连字符。

+0

您可以在某处描述“ - ”的目的以及它如何指示PS执行此操作时引用文档吗? –

+0

[This answer](http://stackoverflow.com/a/12198146/1630171)从@ravikanth到一个类似的问题引用了“Windows PowerShell in Action”,但除此之外我没有一个源代码。它与其他shell一致,但是(例如'bash')。 –

+0

下面是在PowerShell中运行可执行文件的源代码,值得一看:http://social.technet.microsoft.com/wiki/contents/articles/7703.powershell-running-executables.aspx – JamieSee

-2

哇。有时候我真的很讨厌powershell。看来解释者认为' - '是减量操作符或其他东西。如果我在 - 参数之前加上转义字符,即使用命令行:

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

一切都很好。

正如我所说,有时我真的很讨厌powershell。希望这可以帮助其他人解决这个问题。

+1

你的解决方案正在工作,但你的解释是错误的。 –

6

PowerShell 3你可以使用 - %来停止正常解析的PowerShell。

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