检测PowerShell开关

3
我正在用C#开发PowerShell cmdlet,其中包含真/假的开关语句。我注意到如果我想要布尔值为true,我需要指定-SwitchName $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)?

1个回答

5

要将参数声明为开关参数,您应该将其类型声明为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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接