POWERSHELL / CHAPTER 07

Splatting and mutually exclusive parameters

Advanced

Represent valid command calls in the function interface.

By the end of this chapter

  • Build named arguments in a hashtable
  • Use parameter sets for exclusive input modes
  • Inspect the selected parameter set intentionally

The idea

Splatting passes a collection of arguments to a command. Hashtable splatting names each parameter, making a larger call easier to inspect and allowing optional parameters to be assembled deliberately. The keys must be actual parameter names, and the values still pass through normal binding, conversion, and validation. A splat is structured argument data, not a string of PowerShell source to execute.

Parameter sets express different valid call shapes, such as choosing a record by identifier or by name. Put each exclusive mandatory parameter in its own set and handle the selected set explicitly through PSCmdlet.ParameterSetName. Supplying incompatible parameters should fail during binding rather than forcing a guess inside the function. Test each valid set, missing mandatory inputs, and the invalid combination of both modes.

PowerShell example
function Get-RecordLabel {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ParameterSetName='ById')][int]$Id,
        [Parameter(Mandatory, ParameterSetName='ByName')][string]$Name
    )
    if ($PSCmdlet.ParameterSetName -eq 'ById') { "id:$Id" }
    else { "name:$Name" }
}
$arguments = @{ Id = 7 }
Get-RecordLabel @arguments
Result
id:7

The hashtable supplies the Id parameter, selecting ById. Binding establishes the valid input mode before the function body runs.

Try it yourself

Create a lookup function with exclusive ByCode and ByLabel parameter sets and call both through splatting.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

A function has Id only in ById and Name only in ByName. What should passing both cause?