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  Curtis Smith 3 months, 1 week ago.

  • Author
    Posts
  • #74933

    Poseyj
    Participant

    $Var1 = "abc"

    $Var2 = "$Var1"

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

  • #74938

    Ben Camareno
    Participant

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

  • #74950

    Curtis Smith
    Participant

    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)"

    Results:

    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.