Multiple powershell switch parameters - can it be optimized? Multiple powershell switch parameters - can it be optimized? powershell powershell

Multiple powershell switch parameters - can it be optimized?


Another thing you could do instead of all those switch parameters is to use a [ValidateSet]

function Get-Data{    [cmdletbinding()]    param(        [Parameter(Mandatory=$true)]        [ValidateSet('Network','Profile','Server','DeviceBay')]        [string]$Item    )    Switch ($Item){        'network' {'Do network stuff'}        'profile' {'Do profile stuff'}        'server' {'Do server stuff'}        'devicebay' {'Do devicebay stuff'}    }}


Probably not the most elegant solution, but using parametersets makes powershell do some of the work for you:

#requires -version 2.0function 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...


You can add the [cmdletbinding()] keyword so you get $PSBoundParameters, and use that for a switch pipeline:

function Get-data{    [cmdletbinding()]    param (        [switch]$network,        [switch]$profile,        [switch]$server,        [switch]$devicebay     )     Switch ($PSBoundParameters.GetEnumerator().      Where({$_.Value -eq $true}).Key)     {       'network'    { 'Do network stuff' }       'profile'    { 'Do profile stuff'  }       'server'     { 'Do server stuff' }       'devicebay'  { 'Do devicebay stuff' }     }}