Create an incrementing variable from 2 variables in PowerShell

You’re looking for variable indirection, i.e. the ability to refer to a variable indirectly, by a name stored in another variable or returned from an expression.

Note, however, that there are usually superior alternatives, such as using arrays or hashtables as multi-value containers – see this answer for an example.

If you do need to use variable indirection, use Get-Variable and Set-Variable:

$week_data1 = 'foo', 'bar'

$i = 1

# Same as: $week_data1
# Note that "$" must NOT be specified as part of the name.
Get-Variable "week_data$i" -ValueOnly

# Same as: $week_data1 = 'baz', 'quux'
Set-Variable "week_data$i" baz, quux

# Updating an existing value requires nesting the two calls:
# Same as: $week_data1 += 'quuz'
Set-Variable "week_data$i" ((Get-Variable "week_data$i" -ValueOnly) + 'quuz')

As an aside: “extending” an array with += is convenient, but inefficient: a new array must be created behind the scenes every time – see this answer.

Similarly, calling cmdlets to set and get variables performs poorly compared to direct assignments and variable references.

See this answer for applying the indirection technique analogously to environment variables, using Get-Content / Set-Content and the Env: drive.


As for what you tried:

  • $week_data$i = ... is an assignment expression, which is interpreted as directly juxtaposing two variables, $week_data and $i, which causes the syntax error you saw.

  • By contrast, something like Write-Output $week_data$i is a command, and while $week_data$i is also interpreted as two variable references, as a command argument it is syntactically valid, and would simply pass the (stringified) concatenation of the two variable values; in other words: $week_data$i acts as if it were double-quoted, i.e. an expandable string, and the command is therefore equivalent to Write-Output "$week_data$i"

Leave a Comment

tech