Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum like switch parameter in PowerShell

Tags:

powershell

I am using switch parameters in my PowerShell script in this fashion.

param(     [switch] $Word,     [switch] $Excel,     [switch] $powerpoint,     [switch] $v2007,     [switch] $v2010,     [switch] $x86,     [switch] $x64, ) 

I am trying to figure out any neat way to have it more enum style. As anyone might guess, I would want the user to choose between word, excel and powerpoint. And between x2007 and v2010.

Is there a neat way to get input params enum style?

I am new to PowerShell. So if this sounds like that I don't know something obvious, then please point me to some link where I can read about it.

like image 548
bits Avatar asked Sep 17 '10 14:09

bits


People also ask

How do I create a switch parameter in PowerShell?

To create a switch parameter in a function, specify the switch type in the parameter definition. Switch parameters are easy to use and are preferred over Boolean parameters, which have a less natural syntax for PowerShell. For example, to use a switch parameter, the user types the parameter in the command.

Does PowerShell have a switch statement?

Like many other languages, PowerShell has commands for controlling the flow of execution within your scripts. One of those statements is the switch statement and in PowerShell, it offers features that aren't found in other languages.

What is param () in PowerShell?

The PowerShell parameter is a fundamental component of any script. A parameter is a way that developers enable script users to provide input at runtime. If a PowerShell script's behavior needs to change in some way, a parameter provides an opportunity to do so without changing the underlying code.


1 Answers

I would use a ValidateSet parameter attribute instead.

From: about_Functions_Advanced_Parameters

The ValidateSet attribute specifies a set of valid values for a parameter or variable. Windows PowerShell generates an error if a parameter or variable value does not match a value in the set.

Example function:

function test-value {     param(         [Parameter(Position=0)]         [ValidateSet('word','excel','powerpoint')]         [System.String]$Application,          [Parameter(Position=1)]         [ValidateSet('v2007','v2010')]         [System.String]$Version     )       write-host "Application: $Application"     write-host "Version: $Version" }      PS > test-value -application foo 

Output:

test-value : Cannot validate argument on parameter 'Application'. The argument "foo" does not belong to the set "word,excel,powerpoint" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again.

like image 198
Shay Levy Avatar answered Sep 20 '22 10:09

Shay Levy