Skip to content

Commit b577c89

Browse files
committed
Explain the proper use of a SwitchParameter
1 parent 211237f commit b577c89

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidDefaultValueSwitchParameter.md

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
description: Switch Parameters Should Not Default To True
3-
ms.date: 06/28/2023
3+
ms.date: 12/05/2024
44
ms.topic: reference
55
title: 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

0 commit comments

Comments
 (0)