powershellif-statementvariablesforeachindirection

If Statement Against Dynamic Variable


I am attempting to do something similar to the following ...

New-Variable -Name "state_$name" -Value "True"
if ("state_$name" -eq "True") {
    Write-Host "Pass"
} else {
    Write-Host "Fail"
}

I have attempted this a number of different ways but it is not working exactly how I would like it to work. I need to write the if statement to account for a dynamic variable as these values will change inside of a foreach loop.

I have provided a simple example above for proof of concept.


Solution

  • Replace

    if ("state_$name" -eq "True") {
    

    with:

    if ((Get-Variable -ValueOnly "state_$name") -eq "True") {
    

    That is, if your variable name is only known indirectly, via an expandable string, you cannot reference it directly (as you normally would with the $ sigil) - you need to obtain its value via Get-Variable, as shown above.

    However, as JohnLBevan points out, you can store the variable object in another (non-dynamic) variable, so that you can then get and set the dynamic variable's value via the .Value property.
    Adding -PassThru to the New-Variable call directly returns the variable object, without the need for a subsequent Get-Variable call:

    $dynamicVarObject = New-Variable -Name "state_$name" -Value "True" -PassThru
    if ($dynamicVarObject.Value -eq "True") {
        "Pass"
    } else {
        "Fail"
    }
    

    That said, there are usually better alternatives to creating variables this way, such as using hashtables:

    $hash = @{}
    $hash.$name = 'True'
    
    if ($hash.$name -eq 'True') { 'Pass' } else { 'Fail' }