【问题标题】:Inserting for loop's variable into another variable names将for循环的变量插入另一个变量名
【发布时间】:2020-01-06 21:58:05
【问题描述】:

我正在尝试简化我的同事所做的 Windows 界面脚本,他在其中使用了很多 if 循环,我认为可以使用 for 循环进一步缩短这些脚本。

基本上,我们有几组计算机,每组 4 到 12 台不等,我们为每个管理员提供了一个界面来恢复他们各自的快照。

我希望用 for 循环中的 $i 值替换每个变量中的数字。

我尝试过使用数组和哈希表,但根据我收集到的信息,它们更适合存储值而不是包含其他变量的公式。

if($ComputerNumber -eq 4) {
   $checkBoxComputer1LocX = $leftMargin
   $checkBoxComputer1LocY = [int]$labelSubHeaderLocY + [int]$buttonHeight + [int]$padding

   $checkBoxComputer2LocX = $leftMargin
   $checkBoxComputer2LocY = [int]$labelSubHeaderLocY + [int]$buttonHeight + [int]$padding + (1 * ([int]$checkBoxHeight + [int]$padding))

   $checkBoxComputer3LocX = $leftMargin
   $checkBoxComputer3LocY = [int]$labelSubHeaderLocY + [int]$buttonHeight + [int]$padding + (2 * ([int]$checkBoxHeight + [int]$padding))

   $checkBoxComputer4LocX = $leftMargin
   $checkBoxComputer4LocY = [int]$labelSubHeaderLocY + [int]$buttonHeight + [int]$padding + (3 * ([int]$checkBoxHeight + [int]$padding))
}

这就是我想要实现的目标:

for($i=1; $i -le $ComputerNumber; i++) {
   $checkBoxComputer$iLocX = $leftMargin
   $checkBOxComputer$iLocY = [int]$labelSubHeaderLocY + [int]$buttonHeight + [int]$padding + (($i - 0) * ([int]$checkBoxHeight + [int]padding))
}

【问题讨论】:

    标签: powershell for-loop variables indirection


    【解决方案1】:

    要为赋值使用变量间接(通过存储在另一个变量中的名称引用变量),使用Set-Variable(对于检索,你会使用Get-Variable):

    for($i=1; $i -le $ComputerNumber; i++) {
      Set-Variable -Name checkBoxComputer${i}LocX -Value $leftMargin
      Set-Variable -Name checkBoxComputer${i}LocY -Value ([int]$labelSubHeaderLocY + [int]$buttonHeight + [int]$padding + (($i - 0) * ([int]$checkBoxHeight + [int]padding)))
    }
    

    请注意变量 $i 的名称如何包含在 {...} (${i}) 中,以便明确地描述它,因此后续字符不会被视为名称的一部分。


    但是,您绝对可以使用 arrays自定义对象 而不是单个变量,这是更可取的:

    [array] $checkBoxes = for($i=1; $i -le $ComputerNumber; i++) {
      [pscustomobject] @{ 
         LocX = $leftMargin
         LocY= [int]$labelSubHeaderLocY + [int]$buttonHeight + [int]$padding + (($i - 0) * ([int]$checkBoxHeight + [int]padding))
      }
    }
    

    上面创建了一个(0-index-based)自定义对象数组,每个对象都有一个.LocX.LocY属性,因此,例如,您可以访问第一个复选框的.LocX值如下:

    $checkBoxes[0].LocX
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      相关资源
      最近更新 更多