Sheeboid
Sheeboid

Reputation: 35

Creating a dynamically-named variable in PowerShell

I'd like to create the variable offsetX, where X is some number. Right now, I use:

new-variable -name offset$i

where $i is an integer. However, what I really want is offset($i-1). How would I change the syntax of the above statement to accomplish this?

My latest attempt was:

new-variable -name offset+"[int]$i-1"

which didn't result in an error being thrown, but still doesn't accomplish my goal.

Upvotes: 2

Views: 2030

Answers (1)

user2555451
user2555451

Reputation:

Put the subtraction part inside $(...), which is known as a SubExpression operator.

Below is a demonstration:

PS > $i = 2 
PS > New-Variable -Name offset$($i - 1) -Value value
PS > $offset1
value
PS > 

Upvotes: 4

Related Questions