问题
I'm developing a PowerShell cmdlet in C#, and have true/false switch statements. I have noted that I need to specify -SwitchName $true, if I want the bool to be true, otherwise I get:
Missing an argument for parameter 'SwitchName'. Specify a parameter of type 'System.Boolean' and try again.
The switch is decorated as such:
[Parameter(Mandatory = false, Position = 1,
, ValueFromPipelineByPropertyName = true)]
How can I just detect the presence of the switch (-SwitchName sets to true, absence of -SwitchName indicates false)?
回答1:
To declare parameter as switch parameter, you should declare it type as System.Management.Automation.SwitchParameter
instead of System.Boolean
. By the way, it is possible to distinguish three state of switch parameter:
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
来源:https://stackoverflow.com/questions/32485249/detecting-a-powershell-switch