【发布时间】:2015-06-11 19:04:19
【问题描述】:
我在 cmdlet Get-DateSlain 上有一个 GetDynamicParameters(),它执行以下操作:
public object GetDynamicParameters()
{
List<string> houseList = {"Stark", "Lannister", "Tully"};
var attributes = new Collection<Attribute>
{
new ParameterAttribute
{
HelpMessage = "Enter a house name",
},
new ValidateSetAttribute(houseList.ToArray()),
};
if (!this.ContainsKey("House"))
{
this.runtimeParameters.Add("House", new RuntimeDefinedParameter("House", typeof(string), attributes));
}
}
这正如预期的那样工作——用户可以输入Get-DateSlain -House,然后在可用的房屋中进行选项卡。但是,一旦选择了房子,我希望能够将结果缩小到该房子中的角色。此外,如果它是房子“斯塔克”,我想允许一个-Wolf 参数。因此要实现(为简洁起见,删除了一些值有效性检查):
public object GetDynamicParameters()
{
if (this.runtimeParameters.ContainsKey("House"))
{
// We already have this key - no need to re-add. However, now we can add other parameters
var house = this.runtimeParameters["House"].Value.ToString();
if (house == "Stark")
{
List<string> characters = { "Ned", "Arya", "Rob" };
var attributes = new Collection<Attribute>
{
new ParameterAttribute
{
HelpMessage = "Enter a character name",
},
new ValidateSetAttribute(characters.ToArray()),
};
this.runtimeParameters.Add("Character", new RuntimeDefinedParameter("Character", typeof(string), attributes));
List<string> wolves = { "Shaggydog", "Snow", "Lady" };
var attributes = new Collection<Attribute>
{
new ParameterAttribute
{
HelpMessage = "Enter a wolf name",
},
new ValidateSetAttribute(wolves.ToArray()),
};
this.runtimeParameters.Add("Wolf", new RuntimeDefinedParameter("Wolf", typeof(string), attributes));
}
else if (house == "Lannister")
{
List<string> characters = { "Jaimie", "Cersei", "Tywin" };
// ...
}
// ...
return this.runtimeParameters;
}
List<string> houseList = {"Stark", "Lannister", "Tully"};
var attributes = new Collection<Attribute>
{
new ParameterAttribute
{
HelpMessage = "Enter a house name",
},
new ValidateSetAttribute(houseList.ToArray()),
};
this.runtimeParameters.Add("House", new RuntimeDefinedParameter("House", typeof(string), attributes));
}
这看起来应该可以工作,但事实并非如此。 GetDynamicParameters 函数仅被调用一次,即在向this.runtimeParameters["House"] 提供值之前。由于在填写该值后它不会重新评估,因此永远不会添加额外的字段,并且ProcessRecord 中依赖这些字段的任何逻辑都将失败。
那么 - 有没有办法让多个相互依赖的动态参数?
【问题讨论】:
标签: c# powershell cmdlets