Skip to content

Latest commit

 

History

History
43 lines (30 loc) · 1.19 KB

AvoidAssignmentToAutomaticVariable.md

File metadata and controls

43 lines (30 loc) · 1.19 KB
description ms.custom ms.date ms.topic title
Changing automatic variables might have undesired side effects
PSSA v1.22.1
06/28/2023
reference
AvoidAssignmentToAutomaticVariable

AvoidAssignmentToAutomaticVariable

Severity Level: Warning

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.

To understand more about automatic variables, see Get-Help about_Automatic_Variables.

How

Use variable names in functions or their parameters that do not conflict with automatic variables.

Example

Wrong

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

function foo($Error){ }
function Get-CustomErrorMessage($ErrorMessage){ $Error = "Error occurred: $ErrorMessage" }

Correct

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