【问题标题】:If Statement Against Dynamic Variable [duplicate]If语句反对动态变量[重复]
【发布时间】:2019-04-21 09:32:33
【问题描述】:

我正在尝试做类似以下的事情......

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

我尝试了多种不同的方法,但它并没有完全按照我希望的方式工作。我需要编写 if 语句来说明动态变量,因为这些值会在 foreach 循环内发生变化。

我在上面提供了一个简单的概念证明示例。

【问题讨论】:

  • 您是否尝试使用Hashtable
  • 原因为什么强烈不推荐使用变量命名的变量。 [grin] 创建 $Var 后很难正确获取名称。 ///// 这个的目标是什么?

标签: powershell if-statement variables foreach indirection


【解决方案1】:

替换

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

与:

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

也就是说,如果您的变量名仅间接通过可扩展字符串知道,则您不能直接引用它(就像您通常使用$ sigil 一样) - 您需要通过Get-Variable获取其值,如上图。

但是,正如JohnLBevan 指出的那样,您可以将变量 object 存储在另一个(非动态)变量中,这样您就可以通过以下方式获取和设置动态变量的值.Value 属性
New-Variable调用中添加-PassThru直接返回变量对象,无需后续Get-Variable调用:

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

也就是说,以这种方式创建变量通常有更好的替代方法,例如使用 hashtables

$hash = @{}
$hash.$name = 'True'

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-25
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 2018-04-28
    • 2015-11-13
    • 2015-06-29
    相关资源
    最近更新 更多