Question:
I am trying to write a simple wrapper that accept one parameter for the output.
This is how it looks now
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function Get-data{ param ( [switch]$network, [switch]$profile, [switch]$server, [switch]$devicebay ) if ($network.IsPresent) { $item = "network"} elseif ($profile.IsPresent) {$item = "profile"} elseif ($server.IsPresent) {$item = "server"} elseif ($devicebay.IsPresent){$item = "devicebay"} $command = "show $item -output=script2" } |
Clearly this could be optimize but I am struggling to wrap my head around on how I can achieve it .Is there some easy way to ensure only single parameter is accepted and used without resorting to multiple elseif statements?
Also I would like to provide array of paramters instead doing it the way it is done at the moment.
Answer:
Probably not the most elegant solution, but using parametersets makes powershell do some of the work for you:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#requires -version 2.0 function Get-data { [cmdletbinding()] param( [parameter(parametersetname="network")] [switch]$network, [parameter(parametersetname="profile")] [switch]$profile, [parameter(parametersetname="server")] [switch]$server, [parameter(parametersetname="devicebay")] [switch]$devicebay ) $item = $PsCmdlet.ParameterSetName $command = "show $item -output=script2" } |
This example will error out if you don’t provide one of the switches, but you could probably provide an extra switch that does nothing or errors more gracefully if you want to account for that case…