powershell - 将for循环的变量插入另一个变量名中

标签 powershell for-loop variables indirection

我正在尝试简化我的同事所做的一个 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))
}

最佳答案

要使用变量间接寻址(通过存储在另一个变量中的名称引用变量)赋值使用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}) 中,以便明确地表示对其进行描述,以便后续字符不被视为名称的一部分。


但是,您绝对可以使用数组自定义对象来代替单个变量,这是更好的选择:

[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-基于索引)自定义对象数组,每个对象都有一个 .LocX.LocY 属性,例如,您可以按如下方式访问第一个复选框的 .LocX 值:

$checkBoxes[0].LocX

关于powershell - 将for循环的变量插入另一个变量名中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57781074/

相关文章:

python - 我的for循环与yield相结合的问题

r - 如何在矩阵上使用 for 循环

variables - 我可以在配置单元中使用变量替换来获取值列表吗?

html - 将变量(cookie)从本地 html 传递到 UILabel - iOS

.net - 如何将get-item cmdlet的输出作为字符串输出到变量

powershell - 我可以使用基于注释的文档为示例添加标题吗?

windows - PowerShell 中 New-ItemProperty 的小问题

Powershell 返回包含特定文件但不完全递归的目录

更改函数名称的javascript代码

node.js - 如何将变量从 Express 传递到 Jade 模板