Detecting a PowerShell Switch Detecting a PowerShell Switch powershell powershell

Detecting a PowerShell Switch


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-ModuleTest-SwitchTest-Switch -SwitchNameTest-Switch -SwitchName: $false