4

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.