MegaBites-AI/Windows-powershell
0372
1---2applyTo:3 - "**/*.ps1"4 - "**/*.psm1"5---6 7# PowerShell Automatic Variables - Naming Guidelines8 9## Purpose10 11This instruction provides guidelines for avoiding conflicts with PowerShell's automatic variables when writing PowerShell scripts and modules.12 13## What Are Automatic Variables?14 15PowerShell has built-in automatic variables that are created and maintained by PowerShell itself. Assigning values to these variables can cause unexpected behavior and side effects.16 17## Common Automatic Variables to Avoid18 19### Critical Variables (Never Use)20 21- **`$matches`** - Contains the results of regular expression matches. Overwriting this can break regex operations.22- **`$_`** - Represents the current object in the pipeline. Only use within pipeline blocks.23- **`$PSItem`** - Alias for `$_`. Same rules apply.24- **`$args`** - Contains an array of undeclared parameters. Don't use as a regular variable.25- **`$input`** - Contains an enumerator of all input passed to a function. Don't reassign.26- **`$LastExitCode`** - Exit code of the last native command. Don't overwrite unless intentional.27- **`$?`** - Success status of the last command. Don't use as a variable name.28- **`$$`** - Last token in the last line received by the session. Don't use.29- **`$^`** - First token in the last line received by the session. Don't use.30 31### Context Variables (Use with Caution)32 33- **`$Error`** - Array of error objects. Don't replace, but can modify (e.g., `$Error.Clear()`).34- **`$PSBoundParameters`** - Parameters passed to the current function. Read-only.35- **`$MyInvocation`** - Information about the current command. Read-only.36- **`$PSCmdlet`** - Cmdlet object for advanced functions. Read-only.37 38### Other Common Automatic Variables39 40- `$true`, `$false`, `$null` - Boolean and null constants41- `$HOME`, `$PSHome`, `$PWD` - Path-related variables42- `$PID` - Process ID of the current PowerShell session43- `$Host` - Host application object44- `$PSVersionTable` - PowerShell version information45 46For a complete list, see: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_automatic_variables47 48## Best Practices49 50### ❌ Bad - Using Automatic Variable Names51 52```powershell53# Bad: $matches is an automatic variable used for regex capture groups54$matches = Select-String -Path $file -Pattern $pattern55 56# Bad: $args is an automatic variable for undeclared parameters57$args = Get-ChildItem58 59# Bad: $input is an automatic variable for pipeline input60$input = Read-Host "Enter value"61```62 63### ✅ Good - Using Descriptive Alternative Names64 65```powershell66# Good: Use descriptive names that avoid conflicts67$matchedLines = Select-String -Path $file -Pattern $pattern68 69# Good: Use specific names for arguments70$arguments = Get-ChildItem71 72# Good: Use specific names for user input73$userInput = Read-Host "Enter value"74```75 76## Naming Alternatives77 78When you encounter a situation where you might use an automatic variable name, use these alternatives:79 80| Avoid | Use Instead |81|-------|-------------|82| `$matches` | `$matchedLines`, `$matchResults`, `$regexMatches` |83| `$args` | `$arguments`, `$parameters`, `$commandArgs` |84| `$input` | `$userInput`, `$inputValue`, `$inputData` |85| `$_` (outside pipeline) | Use a named parameter or explicit variable |86| `$Error` (reassignment) | Don't reassign; use `$Error.Clear()` if needed |87 88## How to Check89 90### PSScriptAnalyzer Rule91 92PSScriptAnalyzer has a built-in rule that detects assignments to automatic variables:93 94```powershell95# This will trigger PSAvoidAssignmentToAutomaticVariable96$matches = Get-Something97```98 99**Rule ID**: PSAvoidAssignmentToAutomaticVariable100 101### Manual Review102 103When writing PowerShell code, always:1041. Avoid variable names that match PowerShell keywords or automatic variables1052. Use descriptive, specific names that clearly indicate the variable's purpose1063. Run PSScriptAnalyzer on your code before committing1074. Review code for variable naming during PR reviews108 109## Examples from the Codebase110 111### Example 1: Regex Matching112 113```powershell114# ❌ Bad - Overwrites automatic $matches variable115$matches = [regex]::Matches($content, $pattern)116 117# ✅ Good - Uses descriptive name118$regexMatches = [regex]::Matches($content, $pattern)119```120 121### Example 2: Select-String Results122 123```powershell124# ❌ Bad - Conflicts with automatic $matches125$matches = Select-String -Path $file -Pattern $pattern126 127# ✅ Good - Clear and specific128$matchedLines = Select-String -Path $file -Pattern $pattern129```130 131### Example 3: Collecting Arguments132 133```powershell134# ❌ Bad - Conflicts with automatic $args135function Process-Items {136 $args = $MyItems137 # ... process items138}139 140# ✅ Good - Descriptive parameter name141function Process-Items {142 [CmdletBinding()]143 param(144 [Parameter(ValueFromRemainingArguments)]145 [string[]]$Items146 )147 # ... process items148}149```150 151## References152 153- [PowerShell Automatic Variables Documentation](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_automatic_variables)154- [PSScriptAnalyzer Rules](https://github.com/PowerShell/PSScriptAnalyzer/blob/master/docs/Rules/README.md)155- [PowerShell Best Practices](https://learn.microsoft.com/powershell/scripting/developer/cmdlet/strongly-encouraged-development-guidelines)156 157## Summary158 159**Key Takeaway**: Always use descriptive, specific variable names that clearly indicate their purpose and avoid conflicts with PowerShell's automatic variables. When in doubt, choose a longer, more descriptive name over a short one that might conflict.160 