header image

PowerShell parameter sets

Posted by: | May 22, 2018 Comments Off on PowerShell parameter sets |

PowerShell parameter sets allow you to control which parameters can be used together. If a parameter isn’t in the parameter set you’re trying to use you’ll get an error message.

PS> Get-VM -Name XYZ -id (New-Guid)
 Get-VM : Parameter set cannot be resolved using the specified named parameters.
 At line:1 char:1
 + Get-VM -Name XYZ -id (New-Guid)
 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 + CategoryInfo : InvalidArgument: (:) [Get-VM], ParameterBindingException
 + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.HyperV.PowerShell.Commands.GetVM

 

You can also use parameter sets to help control the processing within your function as this example shows:

function Convert-Temperature {
param (
[Parameter(ParameterSetName='Celsius')]
[double]$degreeC,

[Parameter(ParameterSetName='Fahrenheit')]
[double]$degreeF,

[Parameter(ParameterSetName='Kelvin')]
[double]$degreeK
)

$temps = New-Object -TypeName psobject -Property @{
'Temperature-Celsius' = 0.0
'Temperature-Fahrenheit' = 0.0
'Temperature-Kelvin' = 0.0
}

switch ($psCmdlet.ParameterSetName) {
"Celsius" {
$temps.'Temperature-Celsius' = $degreeC
$temps.'Temperature-Fahrenheit' = [math]::Round((32 + ($degreeC * 1.8)), 2)
$temps.'Temperature-Kelvin' = $degreeC + 273.15
}

"Fahrenheit" {
$temps.'Temperature-Celsius' = [math]::Round((($degreeF - 32) / 1.8), 2)
$temps.'Temperature-Fahrenheit' = $degreeF
$temps.'Temperature-Kelvin' = $temps.'Temperature-Celsius' + 273.15
}

"Kelvin" {
$temps.'Temperature-Celsius' = $degreeK - 273.15
$temps.'Temperature-Fahrenheit' = [math]::Round((32 + ($temps.'Temperature-Celsius' * 1.8)), 2)
$temps.'Temperature-Kelvin' = $degreeK
}

default {Write-Error -Message "Error!!! Should not be here" }
}

$temps
}

 

Each of the input parameters is in its own parameter set meaning that they are mutually exclusive – you can only use one of them!

The switch statement uses the active parameter set name to decide how to perform the relevant conversions – the output object contains the temperature in Celsius, Fahrenheit and Kelvin

under: PowerShell

Comments are closed.

Categories