【问题标题】:PowerShell command line parameters and '--'PowerShell 命令行参数和“--”
【发布时间】:2013-03-24 16:41:35
【问题描述】:

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

例如,我提供命令行:

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

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

foo.txt bar --

而不是

foo.txt -- bar --

正如预期的那样。

为什么会这样?

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

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

它按预期工作。

另外,称它为:

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

似乎没有帮助。

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

【问题讨论】:

  • 进一步说明。显然,这两个“--”并不是问题的全部。似乎powershell dropbx 第一个'--',即使第二个不存在。似乎 -- 必须对 powershell 有特殊含义。

标签: powershell command-line powershell-2.0


【解决方案1】:

双连字符指示 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

为避免这种行为,您必须引用 ("--", '--') 或转义 (`--) 双连字符。

【讨论】:

  • 您能否在某处引用 doc 来描述“--”的目的以及它如何指示 PS 执行此操作?
  • This answer from @ravikanth 到一个类似的问题引用了“Windows PowerShell in Action”,但除此之外我没有来源。不过,它与其他 shell 一致(例如bash)。
  • 这是一个在 PowerShell 中运行可执行文件的源代码,非常值得一看:social.technet.microsoft.com/wiki/contents/articles/…
  • @JamieSee 我没有看到那篇文章中讨论的双破折号,只有 PowerShell v3 引入的“停止解析”参数 (--%)。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2019-08-05
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2019-06-21
    • 2016-03-25
    相关资源
    最近更新 更多