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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With