| description | Avoid dynamic variable names, instead use a hash table or similar dictionary type. |
|---|---|
| ms.date | 04/21/2026 |
| ms.topic | reference |
| title | AvoidDynamicallyCreatingVariableNames |
Severity Level: Information
Do not create variables with a dynamic name, this might introduce conflicts with other variables and is difficult to maintain.
Use a hash table or similar dictionary type to store values with dynamic keys.
'One', 'Two', 'Three' | ForEach-Object -Begin { $i = 1 } -Process {
New-Variable -Name "My$_" -Value ($i++)
}
$MyTwo # returns 2$My = @{}
'One', 'Two', 'Three' | ForEach-Object -Begin { $i = 1 } -Process {
$My[$_] = $i++
}
$My.Two # returns 2When a specific scope, option, or visibility is required, put the dictionary (hash table) in that scope and apply the appropriate option or visibility. For example, if the values should be read-only and available in the script scope, put the hash table in the script scope and make it read-only.
New-Variable -Name My -Value @{} -Option ReadOnly -Scope Script
'One', 'Two', 'Three' | ForEach-Object -Begin { $i = 1 } -Process {
$Script:My[$_] = $i++
}
$Script:My.Two # returns 2