File tree Expand file tree Collapse file tree 1 file changed +26
-4
lines changed
reference/docs-conceptual/PSScriptAnalyzer/Rules Expand file tree Collapse file tree 1 file changed +26
-4
lines changed Original file line number Diff line number Diff line change 11---
22description : Switch Parameters Should Not Default To True
3- ms.date : 06/28/2023
3+ ms.date : 12/05/2024
44ms.topic : reference
55title : AvoidDefaultValueSwitchParameter
66---
@@ -10,11 +10,19 @@ title: AvoidDefaultValueSwitchParameter
1010
1111## Description
1212
13- Switch parameters for commands should default to false.
13+ If your parameter takes only ` true ` and ` false ` , define the parameter as type ` [Switch] ` . PowerShell
14+ treats a switch parameter as ` true ` when it's used with a command. If the parameter isn't included
15+ with the command, PowerShell considers the parameter to be false. Don't define ` [Boolean] `
16+ parameters.
17+
18+ You shouldn't define a switch parameter with a default value of ` $true ` because this isn't the
19+ expected behavior of a switch parameter.
1420
1521## How
1622
17- Change the default value of the switch parameter to be false.
23+ Change the default value of the switch parameter to be ` $false ` or don't provide a default value.
24+ Write the logic of the script to assume that the switch parameter default value is ` $false ` or not
25+ provided.
1826
1927## Example
2028
@@ -48,8 +56,22 @@ function Test-Script
4856 $Param1,
4957
5058 [switch]
51- $Switch=$False
59+ $Switch
5260 )
61+
62+ begin {
63+ # Ensure that the $Switch is set to false if not provided
64+ if (-not $PSBoundParameters.ContainsKey('Switch')) {
65+ $Switch = $false
66+ }
67+ }
5368 ...
5469}
5570```
71+
72+ ## More information
73+
74+ - [ Strongly Encouraged Development Guidelines] [ 01 ]
75+
76+ <!-- link references -->
77+ [ 01 ] : /powershell/scripting/developer/cmdlet/strongly-encouraged-development-guidelines#parameters-that-take-true-and-false
You can’t perform that action at this time.
0 commit comments