Tre*_*ard 2 c# powershell pscmdlet
我正在使用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.
Run Code Online (Sandbox Code Playgroud)
开关装饰如下:
[Parameter(Mandatory = false, Position = 1,
, ValueFromPipelineByPropertyName = true)]
Run Code Online (Sandbox Code Playgroud)
我怎样才能检测到交换机的存在(-SwitchName设置为true,缺少-SwitchName表示为false)?
要将参数声明为switch参数,您应该将其声明为type 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
677 次 |
| 最近记录: |