让 shell 解析或做你自己的解析 (powershell/cmd) [英] Let the shell parse or do your own parsing (powershell/cmd)

查看:26
本文介绍了让 shell 解析或做你自己的解析 (powershell/cmd)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个带有命令行参数的应用程序,并在 cmd shell 和 powershell 中使用它.很明显,在我的应用程序的 main() 中接收的参数不同.

I develop an application with command line parameters and use it in cmd shell and powershell. There it is obvious that the arguments are received differently in main() of my application.

static void Main(string[] args)
{
  // In cmd shell:  args[0] == "-ipaddress=127.0.0.1"
  // In powershell: args[0] == "-ipaddress=127"
  //            and args[1] == ".0.0.1"
}

示例:myApp.exe -ipaddress=127.0.0.1

Example: myApp.exe -ipaddress=127.0.0.1

在我的 C# 应用程序中,参数的解释取决于我启动应用程序的 shell.

In my C# application the arguments are interpreted differently depending on the shell I start the app in.

  • 在 cmd shell 中:arg[0]=-ipaddress=127.0.0.1
  • 在 powershell 中:arg[0]=-ipaddress=127 和 arg[1]=.0.0.1

这里的最佳实践是什么?

What is best practice here?

  • 我应该加入所有 args[] 并解析我的应用程序中的参数吗?
  • 我应该依赖 shell 的解析器吗?

推荐答案

tl;dr:

当从 PowerShell 调用 时,将整个参数括在 '...'(单引号)中以确保它按原样传递:

When calling from PowerShell, enclose the entire argument in '...' (single quotes) to ensure that it is passed as-is:

myApp.exe '-ipaddress=127.0.0.1'

<小时>

您遇到了解析错误[1]其中 PowerShell 在第一个 .


You've run into a parsing bug[1] where PowerShell breaks an unquoted argument that starts with - in two at the first .

以下简化示例说明:

# Helper function that echoes all arguments.
function Out-Argument { $i = 0; $Args | % { 'arg[{0}]: {1}' -f ($i++), $_ }}

# Pass an unquoted argument that starts with "-" and has an embedded "."
Out-Argument -foo=bar.baz

以上产生:

arg[0]: -foo=bar
arg[1]: .baz

<小时>

[1] 从 Windows PowerShell v5.1/PowerShell Core v6.0.1 开始就存在推定的bug,并且已经在 GitHub 上报告.
该错误的 PSv2 变体会影响 . 当包含在 interior 中的 "..." 中时 的论点 - 请参阅我的这个答案.


[1] The presumptive bug is present as of Windows PowerShell v5.1 / PowerShell Core v6.0.1 and has been reported on GitHub.
A PSv2 variation of the bug affects . when enclosed in "..." in the interior of the argument - see this answer of mine.

这篇关于让 shell 解析或做你自己的解析 (powershell/cmd)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆