If Statement Against Dynamic Variable [duplicate]

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' }

Leave a Comment