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

查看:180
本文介绍了让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#应用​​程序中,根据我在其中启动应用程序的外壳,对参数的解释不同.

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 []并解析应用程序中的参数吗?
  • 我应该依靠外壳的解析器吗?

推荐答案

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 .

下面的简化示例说明了这一点:

The following simplified example demonstrates that:

# 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 ,并且已 中包含时,会影响. -请参见


[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天全站免登陆