Skip to content

Commit

Permalink
Explain the proper use of a SwitchParameter
Browse files Browse the repository at this point in the history
  • Loading branch information
sdwheeler committed Dec 5, 2024
1 parent 211237f commit b577c89
Showing 1 changed file with 26 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
description: Switch Parameters Should Not Default To True
ms.date: 06/28/2023
ms.date: 12/05/2024
ms.topic: reference
title: AvoidDefaultValueSwitchParameter
---
Expand All @@ -10,11 +10,19 @@ title: AvoidDefaultValueSwitchParameter

## Description

Switch parameters for commands should default to false.
If your parameter takes only `true` and `false`, define the parameter as type `[Switch]`. PowerShell
treats a switch parameter as `true` when it's used with a command. If the parameter isn't included
with the command, PowerShell considers the parameter to be false. Don't define `[Boolean]`
parameters.

You shouldn't define a switch parameter with a default value of `$true` because this isn't the
expected behavior of a switch parameter.

## How

Change the default value of the switch parameter to be false.
Change the default value of the switch parameter to be `$false` or don't provide a default value.
Write the logic of the script to assume that the switch parameter default value is `$false` or not
provided.

## Example

Expand Down Expand Up @@ -48,8 +56,22 @@ function Test-Script
$Param1,
[switch]
$Switch=$False
$Switch
)
begin {
# Ensure that the $Switch is set to false if not provided
if (-not $PSBoundParameters.ContainsKey('Switch')) {
$Switch = $false
}
}
...
}
```

## More information

- [Strongly Encouraged Development Guidelines][01]

<!-- link references -->
[01]: /powershell/scripting/developer/cmdlet/strongly-encouraged-development-guidelines#parameters-that-take-true-and-false

0 comments on commit b577c89

Please sign in to comment.