If Statement Against Dynamic Variable [duplicate]

核能气质少年 提交于 2019-12-28 19:36:51

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/53367597/if-statement-against-dynamic-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!