0

Is it possible to increment count on variable objects in Powershell?

Example:

$var1 = "This"
$var2 = "Is"
$var3 = "A Test"

1..3 | ForEach-Object {$var$_ = DoSometing}

Reason I am asking this, is because I am creating a GUI with system.Windows.Forms.CheckBox. I have several checkbox objects in variables that end with a number I want to manipulate.

$Checkbox1
$Checkbox2
$Checkbox3
$Checkbox4

I am wondering if there is a clean and good way to manipulate these objects with an Foreach-Object. Instead of manipulating each object seperatly.

2
  • 1
    What you're trying to do is ill-advised. Don't do it. Use an array instead: $var = 1..3 | ForEach-Object { DoSomething }. Commented Apr 24, 2019 at 12:12
  • Don't think New-variable will help much here. I think for your usecase, you could better loop over the Controls inside your Form object. eg: $Form.Controls. Simply loop over all controls and then check it by name, type or group. Hope it helps! Commented Apr 24, 2019 at 12:24

1 Answer 1

0

If you really need to create variables, then this can be done with the New-Variable command.

Foreach ($z in (1..3)) {
    New-Variable -Name "Var$z" -Value $z
}

$var1,$var2,$var3
1
2
3

If you need to retrieve or update values for already existing variables, then similarly you can use Get-Variable and Set-Variable.

Foreach ($z in (1..3)) {
    Set-Variable -Name "Var$z" -Value "Updated $z"
    Get-Variable "Var$z" -ValueOnly
}

Updated 1
Updated 2
Updated 3
Sign up to request clarification or add additional context in comments.

1 Comment

The variables are already created and contain data. I want to manipulate the data of variable 1 to 9 in a loop if this is possible. Alternatively I can manipulate the data the normal way, but this would create a lot of extra code and work when the script changes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.