Document the implications of passing an explicit value to a switch parameter #11797
Open
3 tasks done
Labels
area-about
Area - About_ topics
area-sdk-docs
Area - SDK docs
issue-doc-bug
Issue - error in documentation
Prerequisites
Get-Foo
cmdlet" instead of "Typo."Links
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters#switch-parameters
https://learn.microsoft.com/en-us/powershell/scripting/developer/cmdlet/types-of-cmdlet-parameters#switch-parameters
Summary
It's possible to pass an explicit boolean value to a switch parameter, either with hash table splatting or
-Param:$bool
syntax.The implications of this (specifically, with an explicit
$false
value) are not currently documented, despite requiring consideration by cmdlet and function authors alike.New-PSSession
is an example of a command that does not take the implications into consideration, resulting in unexpected behavior for the user.Details
Parameter sets are tied to the presence of the switch, not the value. Modifying command behavior based on the parameter set is problematic if a switch controls which parameter set is chosen.
For real-world examples where this is problematic, see:
Get-Uptime -Since
ignores an explicit$false
value PowerShell/PowerShell#25015As of v7.6.0, there are at least 10 commands shipped with PowerShell that ignore an explicit
$false
switch value due to using the above practice. See Treat-Switch:$false
the same as omitting a switch when selecting a parameter set PowerShell/PowerShell#25027 (comment) for details. These commands subvert reasonable user expectation when the switch is passed an explicit$false
value.Get-Random -Shuffle
Get-SecureRandom -Shuffle
Get-TimeZone -ListAvailable
New-PSSession -UseWindowsPowerShell
Register-PSResourceRepository -PSGallery
Split-Path -Qualifier
/-NoQualifier
/-Leaf
/-IsAbsolute
(not-Extension
/-LeafBase
)Test-Connection -Repeat
/-MtuSize
/-Traceroute
Where-Object
(all non-common switch parameters)Get-Uptime -Since
New-Guid -Empty
Using
InvocationInfo.BoundParameters
/$PSBoundParameters
without checking both the key and value is similarly problematic and should generally be avoided. E.g.,ContainsKey()
reflects the presence of the switch, irrespective of it being passed an explicit value.The natural alternative to using switch-controlled parameter sets is to instead use a single, enum/set-based parameter and branch off that instead (though of course this is not always a viable option). For example:
Note: The proposal in Treat
-Switch:$false
the same as omitting a switch when selecting a parameter set PowerShell/PowerShell#25027 seeks to address the outlined parameter set issue systematically.The text was updated successfully, but these errors were encountered: