How to determine if a PowerShell command-line option value has been specified?

In PowerShell 1.0, if I have a cmdlet parameter for an enumeration type, what is the recommended method for checking if the user specified this parameter on the cmdlet command line? For example:

MyEnum : int { No = 0, Yes = 1, MaybeSo = 2 }

class DoSomethingCommand : PSCmdlet
...
private MyEnum isEnabled;

[Parameter(Mandatory = false)]
public MyEnum IsEnabled
{
    get { return isEnabled; }
    set { isEnabled = value; }
}

protected override void ProcessRecord()
{
    // How do I know if the user passed -IsEnabled <value> to the cmdlet?
}

Is there a way to do this without an isEnabled seed with a dummy value? By default, it will be 0, and I don’t want the seed of each parameter or add a dummy value to my enumeration. I potentially got many cmdlets with 100 parameters, there should be a better way. This is related to this question , but I was looking for a cleaner way to do this. Thank you

+5
5

, .

[Parameter(Mandatory = false)]
public MyEnum? IsEnabled { get; set; }

? MyEnum. , :

if (this.IsEnabled.HasValue) { ... }
+8

PowerShell , , 0 . 0 . - "Unset".

, PowerShell , .NET.

  • Oisin
+4

, , , 0 Unknown - .

, , - . , , 0.

+1
source

I know this thread is a bit outdated, but the best way to do this is to declare your parameter using the SwitchParameter type. Then your users do not need to pass -IsEnabled, they will just add something like -Enabled as a parameter.

Then you check the .IsPresent property of your parameter to see if the caller has been added -Enabled to invoke the cmdlet.

+1
source
bool wasSpecified = MyInvocation.BoundParameters.ContainsKey("IsEnabled");
0
source

All Articles