Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach loop to modify variable

Tags:

powershell

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?

like image 306
LightningWar Avatar asked Oct 20 '25 15:10

LightningWar


1 Answers

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.

like image 137
G42 Avatar answered Oct 22 '25 05:10

G42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!