How can I assign a value to a variable whose name is in the form of a str val?

This topic contains 2 replies, has 3 voices, and was last updated by Profile photo of Curtis Smith Curtis Smith 2 weeks ago.

  • Author
  • #74933
    Profile photo of Poseyj

    $Var1 = "abc"

    $Var2 = "$Var1"

    Without referencing $Var1 directly and only using $Var2's string content, how do I assign "def" to $Var1?

  • #74938
    Profile photo of Ben Camareno
    Ben Camareno

    More context about what you're trying to accomplish would be very helpful 🙂

  • #74950
    Profile photo of Curtis Smith
    Curtis Smith

    You would set $var2 as a reference to $var1

    $var1 = "abc"
    $var2 = [ref]$var1
    Write-Host -ForegroundColor Cyan "Initial Values"
    "`$var1 = $var1"
    "`$var2.value = $($var2.Value)"
    Write-Host -ForegroundColor Cyan "Set New Value via `$var2.value"
    $var2.Value = "def"
    "`$var1 = $var1"
    "`$var2.value = $($var2.Value)"


    Initial Values
    $var1 = abc
    $var2.value = abc
    Set New Value via $var2.value
    $var1 = def
    $var2.value = def

You must be logged in to reply to this topic.