我在C#中开发PowerShell cmdlet,并且有true / false switch语句。我注意到我需要指定-SwitchName $ true,如果我想要bool为true,否则我得到:
Missing an argument for parameter 'SwitchName'. Specify a parameter of type 'System.Boolean' and try again.
开关装饰如下:
[Parameter(Mandatory = false, Position = 1,
, ValueFromPipelineByPropertyName = true)]
如何才能检测到交换机的存在(-SwitchName设置为true,缺少-SwitchName表示为false)?
答案 0 :(得分:5)
要将参数声明为switch参数,您应该将其声明为System.Management.Automation.SwitchParameter
而不是System.Boolean
。顺便说一句,可以区分开关参数的三种状态:
Add-Type -TypeDefinition @'
using System.Management.Automation;
[Cmdlet(VerbsDiagnostic.Test, "Switch")]
public class TestSwitchCmdlet : PSCmdlet {
private bool switchSet;
private bool switchValue;
[Parameter]
public SwitchParameter SwitchName {
set {
switchValue=value;
switchSet=true;
}
}
protected override void BeginProcessing() {
WriteObject(switchSet ? "SwitchName set to \""+switchValue+"\"." : "SwitchName not set.");
}
}
'@ -PassThru|Select-Object -ExpandProperty Assembly|Import-Module
Test-Switch
Test-Switch -SwitchName
Test-Switch -SwitchName: $false