LightningWar
LightningWar

Reputation: 975

Foreach loop to modify variable

I'm learning PowerShell and trying to set variable values inside a loop. Using these strings:

$Apple = 'Apple'
$Banana = 'Banana'
$Orange = 'Orange'

I'm trying to join the strings inside a loop:

$Fruits = @($Apple, $Banana, $Orange)
foreach ($Fruit in $Fruits)
{
    $Fruit = $Fruit + '.' + "Test"
    $Fruit
}

This works inside the scope of the loop. But how can I set the value of $Apple, $Banana and $Orange permanently?

Upvotes: 4

Views: 6782

Answers (1)

G42
G42

Reputation: 10019

You could use a combination of Get-Variable and Set-Variable. Bear in mind the array contains the variable names, not their values.

$Apple  = 'Apple'
$Banana = 'Banana'
$Orange = 'Orange'

$FruitVariables = @('Apple','Banana','Orange')

foreach ($Fruit in $FruitVariables)
{
    Set-Variable -Name $Fruit -Value ((Get-Variable -Name $Fruit).Value + ".Test")
}

If you're only interested in setting the values in the array, you could use index:

$Fruits = @($Apple, $Banana, $Orange)
foreach ($i in 0..($Fruits.Count - 1))
{
    $Fruits[$i] = $Fruits[$i] + '.' + "Test"
    $Fruits[$i]
}

I feel like there may be a more elegant solution using [ref], but the above is what's in the scope of my knowledge.

Upvotes: 2

Related Questions