Detecting a PowerShell Switch

喜你入骨 提交于 2021-02-10 04:22:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!