由于变量中的实际值而改变了几个变量的值

问题描述 投票:0回答:2

我从文件中提取了很多值,并根据每个变量的值af通过foreach循环更改值。但有些情况并没有像我预期的那样......有一个例子:

$a="1"  
$B="2"  
$C="3"  
$D=$a, $b, $c  
Foreach ($Element in $C)  
{  
  If ($Element -eq "1")
  {
    $Element ="Red"
  }
  Elseif ($Element -eq "2")
  {
    $Element = "Green"
  }
  Else 
  {
    $Element = "Blue"
  }
}  

我所期待的是$a$b$c的值从123变为RedGreenBlue

我做错了什么?

powershell
2个回答
0
投票

试试这个 -

$a="1"  
$B="2"  
$C="3"  
$D=$a,$b,$c  
Foreach ($Element in $D)  
{  
If ($Element -eq "1")
{
$a ="Red"
}
Elseif ($Element -eq "2")
{
$b = "Green"
}
Else 
{
$c = "Blue"
}
}  

您的代码中有两点需要注意。首先,你没有迭代$D(你是为$C做的)。 $c只有一个元素,你不需要一个foreach循环。第二,在foreach循环中,你只是改变$element的值,而不是$a$b$c的值。修复这些错误,你很高兴。


0
投票

你正在循环$C中的元素,而数组实际上是$D,但这种改变本身并不能解决它。

解决方案取决于变量a - > c中的对象类型。如果它们是intbool ++,它们是值类型,它们只是在循环中复制到$Element。在循环中修改$Element只会更新存储在$Element中的值,而$a保持不变。

但是,如果变量包含作为引用类型的“普通对象”,则$Element包含指向对象的指针,对$Element的修改也将反映在$a中。

虽然你的例子中的string实际上是一个引用类型,但它的行为类似于一个值类型($Element =..不更新$a),因为它是不可变的,这意味着它不会改变,但实际上每次修改都会创建一个新对象。

您可以使用Get-Variable通过在数组中传入变量名来访问变量。这样,它将支持这两种类型。例:

#Sample objects
$a=[pscustomobject]@{MyProperty="1"}
$B=[pscustomobject]@{MyProperty="2"}
$C="3"

$AutoUpdateVariables="a","b","c"

#If variables are value-type (ex. int), just remove .MyProperty
Foreach ($element in (Get-Variable -Name $AutoUpdateVariables))
{  
    If ($element.Value.MyProperty -eq "1")
    {
        $element.Value.MyProperty ="Red"
    }
    Elseif ($element.Value.MyProperty -eq "2")
    {
        $element.Value.MyProperty = "Green"
    }
    Elseif (-not $element.Value.MyProperty)
    {
        #If MyProperty doesn't exist/is null, set variable to "Blue"
        $element.Value = "Blue"
    }
}

更新:如果您只需要在执行时转换值,则可以创建函数或哈希表,例如:

$a="1"
$B="2"
$C="3"

$HashTable = @{
    "1" = "Red"
    "2" = "Green"
    "3" = "Blue"
}

#As a string value
"Hello '$a' you value should be '$($HashTable[$a])'"
"Hello '$b' you value should be '$($HashTable[$b])'"

#or as a parameter
Get-ChildItem -Path ($HashTable[$c])
© www.soinside.com 2019 - 2024. All rights reserved.