【发布时间】:2011-11-05 03:26:46
【问题描述】:
下面是典型的OptionSet构造代码:
var p = new OptionSet {
{ "h|help", "Show this help", v => { isHelp = (v != null); } },
};
var extra = p.Parse(args);
我的相同代码的Powershell版本是:
$p = New-Object NDesk.Options.OptionSet
$p.Add("h|help", "Show this help", { param([string]$v) $global:isHelp = $true })
$extra = $p.Parse($args)
不幸的是,它有两个问题。当我执行第二行时,我得到了这个:
Multiple ambiguous overloads found for "Add" and the argument count: "3".
At C:\Work\hg\utils\HgTagPromotedBuild.ps1:62 char:7
+ $p.Add <<<< ("h|help", "Show this help message", { param([string]$v) $global:isHelp =
$true })
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
然后执行下一行结果:
Cannot convert argument "0", with value: "System.Object[]", for "Parse" to type "System
.Collections.Generic.IEnumerable`1[System.String]": "Cannot convert the "System.Object[
]" value of type "System.Object[]" to type "System.Collections.Generic.IEnumerable`1[Sy
stem.String]"."
At C:\Work\hg\utils\HgTagPromotedBuild.ps1:63 char:18
+ $extra = $p.Parse <<<< ($args)
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
OptionSet 声明的相关部分是:
public OptionSet Add(Option option);
public OptionSet Add(string prototype, OptionAction<string, string> action);
public OptionSet Add<TKey, TValue>(string prototype, OptionAction<TKey, TValue> action);
public OptionSet Add<T>(string prototype, Action<T> action);
public OptionSet Add(string prototype, Action<string> action);
public OptionSet Add<TKey, TValue>(string prototype, string description, OptionAction<TKey, TValue> action);
public OptionSet Add(string prototype, string description, OptionAction<string, string> action);
public OptionSet Add<T>(string prototype, string description, Action<T> action);
public OptionSet Add(string prototype, string description, Action<string> action);
我根本不明白第一个错误发生了什么。
第二个很清楚 - 显然$args 输入为object[],而OptionSet.Parse 期望IEnumerable<string>,但我找不到如何转换为string[]。
那么,我的问题是如何在没有这些讨厌的异常的情况下将原始 C# 代码转换为 Powershell?
谢谢。
编辑
感谢所有让我明白 PowerShell 有一个定义明确的方法来处理命令行参数的人。我已经承认了这一事实,甚至创建了一个专门的 SO 问题 - Is there a decent command line parser for powershell?,我已经将其标记为已回答。再次感谢大家。
现在,如果可能的话,我仍然想知道如何从 PowerShell 调用特定的 .NET 代码。没有连接到命令行参数解析。只是对知识的纯粹追求。
【问题讨论】:
-
你能说出你想要达到的目标吗?或者甚至可能就如何在 PowerShell 中实现这一点提出一个单独的问题?你问如何使用不应该在 PowerShell for PowerShell 中使用的工具。
-
尝试将第三个参数明确地转换为您需要的类型(Action
?)。此外,在 PowerShell(v2,希望 v3 会有所不同)中使用泛型方法并不容易。看看这篇文章(希望,这会有所帮助):leeholmes.com/blog/2007/06/19/… -
我该如何转换为 Action
?
标签: powershell