问题描述
我正在尝试做类似于以下的事情......
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"
}
我已经尝试了多种不同的方法,但它并没有完全按照我希望的方式工作.我需要编写 if 语句来说明动态变量,因为这些值将在 foreach
循环内更改.
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.
推荐答案
替换
if ("state_$name" -eq "True") {
与:
if ((Get-Variable -ValueOnly "state_$name") -eq "True") {
也就是说,如果你的变量名只是间接,通过一个可扩展的字符串,你不能直接引用它(就像你通常使用 $
符号一样) -您需要通过Get-Variable
获取其值,如上所示.
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.
但是,正如 JohnLBevan 指出的那样,您可以存储变量 object在另一个(非动态)变量中,以便您可以通过 .Value
属性获取和设置动态变量的值.
在New-Variable
调用中添加-PassThru
直接返回变量对象,不需要后续的Get-Variable
调用:
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"
}
也就是说,以这种方式创建变量通常有更好的替代方法,例如使用哈希表:
$hash = @{}
$hash.$name = 'True'
if ($hash.$name -eq 'True') { 'Pass' } else { 'Fail' }
这篇关于If 声明反对动态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!