PowerShell Parameter Sets
A parameter set is a group of parameters that belong together for one way of calling a function. It lets one function offer two different call shapes instead of one confusing shape.
Find by title uses the ByTitle set
Supplying a title picks the ByTitle set, and the body runs its branch.
function Find-Book {
[CmdletBinding()]
param(
[Parameter(ParameterSetName = "ByTitle")][string]$Title,
[Parameter(ParameterSetName = "ById")][int]$Id,
[string]$Note
)
if ($PSCmdlet.ParameterSetName -eq "ByTitle") {
"Set ByTitle, title: $Title, note: $Note"
} else {
"Set ById, id: $Id, note: $Note"
}
}
Find-Book -Title "Dune" -Note "classic"Find by id uses the ById set
Supplying an id picks the ById set instead, and the other branch runs.
function Find-Book {
[CmdletBinding()]
param(
[Parameter(ParameterSetName = "ByTitle")][string]$Title,
[Parameter(ParameterSetName = "ById")][int]$Id,
[string]$Note
)
if ($PSCmdlet.ParameterSetName -eq "ByTitle") {
"Set ByTitle, title: $Title, note: $Note"
} else {
"Set ById, id: $Id, note: $Note"
}
}
Find-Book -Id 42 -Note "rare"Read the set name directly
The function can print the set name itself to show which way it was called.
function Find-Book {
[CmdletBinding()]
param(
[Parameter(ParameterSetName = "ByTitle")][string]$Title,
[Parameter(ParameterSetName = "ById")][int]$Id
)
"Set: " + $PSCmdlet.ParameterSetName
}
Find-Book -Id 9Example
function Find-Book {
[CmdletBinding()]
param(
[Parameter(ParameterSetName = "ByTitle")][string]$Title,
[Parameter(ParameterSetName = "ById")][int]$Id,
[string]$Note
)
if ($PSCmdlet.ParameterSetName -eq "ByTitle") {
"Set ByTitle, title: $Title, note: $Note"
} else {
"Set ById, id: $Id, note: $Note"
}
}
Find-Book -Title "Dune" -Note "classic"
Find-Book -Id 42 -Note "rare"Key points
- ParameterSetName: a label that puts a parameter into one named set.
- Use parameter sets when one function has two different ways to be called.
- $PSCmdlet.ParameterSetName: a value inside the function that tells which set the caller used.
- A parameter with no set name belongs to every set.
- The function body reads the set name and runs the matching branch.
In this example, one function offers two call shapes, and a shared note parameter belongs to both sets. The first call uses a title and the second uses an id, so each prints its own set branch.
Note
Each set has its own parameters, so the caller supplies only the ones for the way they chose.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A function has sets ByName and ById. The call uses -Id 5. What does $PSCmdlet.ParameterSetName hold?