【问题标题】:How can I create a Powershell Cmdlet parameter in C# that behaves as a switch?如何在 C# 中创建一个充当开关的 Powershell Cmdlet 参数?
【发布时间】:2020-11-26 01:36:08
【问题描述】:

我在 C# 中使用 System.Management.Automation 命名空间,以便在 Powershell 模块中公开我的类库。在某些 cmdlet 中,我想提供一个行为类似于开关的可选参数(即,如果包含它,则该参数设置为 true)。我已经看到其他 Powershell Cmdlet 中的参数以这种方式运行,但我还没有看到使用 C# 接口完成此操作的方法。我能来的最接近的是接受布尔值的参数:

[Parameter(HelpMessage = "If enabled, no confirmation prompt will appear")]
public bool Quiet { get; set; } = false;

但是在执行中,参数本身是不能接受的,它需要带有一个值:

New-Widget -Path C:\temp\myfile.abc -Quiet $True

如果可能的话,我希望 Quiet 能够通过参数设置为 true:

New-Widget -Path C:\temp\myfile.abc -Quiet

这可能吗?

【问题讨论】:

标签: c# powershell


【解决方案1】:

您要查找的类型是SwitchParameter,而不是bool

用于在函数的 cmdlet 脚本上定义参数的类型,只能用作开关。

所以你想要的参数签名是:

[Parameter(HelpMessage = "If enabled, no confirmation prompt will appear")]
public SwitchParameter Quiet { get; set; } = false;

bool 存在隐式转换(两种方式),因此它应该是现有 cmdlet 类中的简单替换。


请注意,由于 SwitchParameter 是 PowerShell 不期望任何参数的唯一参数类型,Command-Name -Quiet $true 实际上不会按照您的想法执行 - $true 标记将被解释为位置或未绑定的参数,与-Quiet 无关。

将显式值传递给SwithParameter 的唯一方法是使用紧密绑定,如下所示:

Command-Name -Quiet:$true

出于这个原因,SwitchParameter默认值应该永远设置为true/$true,因为它会强制用户使用如上所示的笨拙的紧密值绑定语法。

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2013-09-16
  • 2020-02-27
  • 2010-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-23
  • 1970-01-01
相关资源
最近更新 更多