首页 > 解决方案 > 在 Powershell 中更改变量名称的“for 循环”

问题描述

我有一个如图所示的功能。它以一个有 8 个值的数组作为参数。

它应该通过 textbox2 -> 检查其中的字符串,如果是,则转到 textbox3 并写入数组的第一个值,一般规则如果 textbox$i 不为空,则在 textbox$i+1 内打印$passarray[$counter] 并加上 $counter + 1。

当它到达一个空的文本框时,该函数将停止。

我这里有几个问题,首先我需要找到一种方法来确保 if 语句内部的单词 $textbox 正在发生变化,$textbox2、$textbox4、$textbox6 等等。

正如这里所写,它不起作用

Function FillBoxes ($passarray) {
 $counter =0
  For ($i=2; $i -lt 17; $i=$i+2){
          if ($textbox$i.textlength -gt 0) {
                $TextBox$i+1.text =  $passarray[$counter]
                $counter++}
                }


 }

how can i do it correcrtly?


标签: windowspowershell

解决方案


我认为 get-variable cmdlet 将解决您的问题。

$i = 2;

$testEcho_2 = 'Hello'

Get-Variable -Name ('testEcho_' + $i) -ValueOnly

Write-Host $(Get-Variable -Name ('testEcho_' + $i) -ValueOnly)

$tmp = ('testEcho_' + $i)

New-Variable -Name "testEcho_$i" -Value 'After Mod' -Force

Write-Host $(Get-Variable -Name ('testEcho_' + $i) -ValueOnly)

另请参阅:在 Powershell 中评估变量中的变量


推荐阅读