> ## Documentation Index
> Fetch the complete documentation index at: https://tally.wharflab.com/llms.txt
> Use this file to discover all available pages before exploring further.

# powershell/PSAvoidDefaultValueSwitchParameter

> Switch Parameters Should Not Default To True

`powershell/PSAvoidDefaultValueSwitchParameter` is a PSScriptAnalyzer diagnostic emitted by tally for PowerShell snippets embedded in Dockerfiles.

| Property | Value             |
| -------- | ----------------- |
| Severity | Warning           |
| Category | PSScriptAnalyzer  |
| Default  | Disabled in tally |
| Auto-fix | No                |

<Note>
  tally disables this rule by default for Dockerfile `RUN` snippets because a `RUN` executes
  statements inline rather than defining cmdlets, parameters, or modules with external callers. Re-enable it with
  `include = ["powershell/PSAvoidDefaultValueSwitchParameter"]` or by setting
  `rules.powershell.PSAvoidDefaultValueSwitchParameter.severity = "warning"` in `.tally.toml`.
</Note>

## Description

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` 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.

## Examples

### Problematic code

```powershell theme={null}
function Test-Script
{
    [CmdletBinding()]
    Param
    (
        [String]
        $Param1,

        [switch]
        $Switch=$True
    )
    ...
}
```

### Correct code

```powershell theme={null}
function Test-Script
{
    [CmdletBinding()]
    Param
    (
        [String]
        $Param1,

        [switch]
        $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]

[01]: https://learn.microsoft.com/powershell/scripting/developer/cmdlet/strongly-encouraged-development-guidelines#parameters-that-take-true-and-false

## Source

This rule documentation is adapted from Microsoft's PSScriptAnalyzer documentation for
[AvoidDefaultValueSwitchParameter](https://github.com/MicrosoftDocs/PowerShell-Docs-Modules/blob/main/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidDefaultValueSwitchParameter.md),
licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).
