diff --git a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidAssignmentToAutomaticVariable.md b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidAssignmentToAutomaticVariable.md index 60d520d..d3cf990 100644 --- a/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidAssignmentToAutomaticVariable.md +++ b/reference/docs-conceptual/PSScriptAnalyzer/Rules/AvoidAssignmentToAutomaticVariable.md @@ -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 --- @@ -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. - +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 @@ -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" } ``` + + + +[01]: /powershell/module/microsoft.powershell.core/about/about_automatic_variables