让shell解析或做你自己的解析(powershell / cmd)

问题描述 投票:1回答:2

我使用命令行参数开发应用程序,并在cmd shell和powershell中使用它。很明显,在我的应用程序的main()中,参数的接收方式不同。

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

在我的C#应用​​程序中,根据我启动应用程序的shell,参数的解释会有所不同。

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

这里的最佳做法是什么?

  • 我应该加入所有args []并解析我的应用程序中的参数吗?
  • 我应该依赖shell的解析器吗?
c# powershell cmd arguments
2个回答
0
投票

我会完全放弃cmd shell支持,只是创建了适当的PowerShell cmdlet。 Writing a Windows PowerShell Cmdlet。但我不知道你的具体要求。

通常,从cmd和PowerShell调用可执行文件应该以相同的方式工作。例如行,“> ping -n 3 google.com”无论你把它放在哪里都能正常工作。


0
投票

tl;博士:

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

myApp.exe '-ipaddress=127.0.0.1'

你遇到了一个解析错误[1],其中PowerShell在第一个-中打破了一个以.开头的不带引号的参数

以下简化示例演示了:

# 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开始,存在推定的错误,并且一直是reported on GitHub。 这个bug的PSv2变种会影响.,当它被包含在"..."的内部时 - 参见我的this answer

© www.soinside.com 2019 - 2024. All rights reserved.