Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
description: Changing automatic variables might have undesired side effects
ms.date: 06/28/2023
ms.date: 05/28/2026
ms.topic: reference
title: AvoidAssignmentToAutomaticVariable
---
Expand All @@ -10,26 +10,22 @@ title: AvoidAssignmentToAutomaticVariable

## Description

PowerShell has built-in variables known as automatic variables. Many of them are read-only and
PowerShell throws an error when trying to assign an value on those. Other automatic variables should
only be assigned in certain special cases to achieve a certain effect as a special technique.
PowerShell automatically defines variables that store internal state information and manages them on
its own. Even though you _can_ override many automatic variables, doing so can have unexpected
effects for users. Assign automatic variables only in advanced, intentional scenarios.

To understand more about automatic variables, see `Get-Help about_Automatic_Variables`.
This rule helps you avoid assignments to automatic variables, which reduces hard-to-diagnose bugs
and keeps function behavior predictable.

<!-- TODO
Ability to suppress was added in https://github.com/PowerShell/PSScriptAnalyzer/pull/1896
Need documentation for how to configure suppression of this rule.
-->
Also use variable names in functions or parameters that don't conflict with automatic variables.

## How

Use variable names in functions or their parameters that do not conflict with automatic variables.
To learn more about automatic variables, see [about_Automatic_Variables][01].

## Example

### Wrong
### Noncompliant

The variable `$Error` is an automatic variables that exists in the global scope and should therefore
The variable `$Error` is an automatic variable that exists in the global scope and should therefore
never be used as a variable or parameter name.

```powershell
Expand All @@ -40,8 +36,12 @@ function foo($Error){ }
function Get-CustomErrorMessage($ErrorMessage){ $Error = "Error occurred: $ErrorMessage" }
```

### Correct
### Preferred

```powershell
function Get-CustomErrorMessage($ErrorMessage){ $FinalErrorMessage = "Error occurred: $ErrorMessage" }
```

<!-- Link reference definitions -->

[01]: /powershell/module/microsoft.powershell.core/about/about_automatic_variables
Loading