如何创建ForEach循环以遍历多个变量Powershell

How to create ForEach loop to go through multiple variables Powershell

我遇到了ForEach循环问题。 我试图遍历相同种类的多个变量只是增加不同。
我试图更改TextBox文本,具体取决于同一行中的Label是否包含文本。

这就是我可以为每个Label编写和IF语句的方式,但是我一直在寻找一种通过ForEach循环循环这些块中的每个块的方法。 我总共有8个标签和文本框。

这是代码:(我确定您会明白我的追求:))

1
2
3
4
5
6
7
IF ( $Label1.Text.Length -ne 0 )
{
    $Label1.Visible = $true
    $TextBox1.Visible = $true

    $TextBox1.Text = ("Enter new name for" + $Label1.Text )
}

ForEach示例

1
2
3
4
5
6
7
8
9
10
11
12
$Count = 1..8

$Count | ForEach-Object {

     IF ( $Label($_).Text.Length -ne 0 )
     {
          $Label($_).Visible = $true
          $TextBox($_).Visible = $true

          $TextBox($_).Text = ("Enter new name for" + $Label($_).Text )
     }
}

等等...

我尝试将变量放入数组并通过这种方式循环,但是当然数组将类型更改为字符串,但它不起作用...


您可以将Get-Variable cmdlet用于该目的:

1
2
3
4
5
6
7
8
9
 1..8 | ForEach-Object {

     if ( (Get-Variable"Label$_").Value.Text.Length -ne 0 )
     {
         (Get-Variable"Label$_").Value.Visible = $true
         (Get-Variable"Label$_").Value.Visible = $true
         (Get-Variable"Label$_").Value.Text = ("Enter new name for" + (Get-Variable"Label$_").Value.Text )
     }
}

试试看,我无法使用label&textbox对象对其进行测试,但是它可以更好地对其进行调整:

1
2
3
4
5
6
7
8
9
10
 1..8  | ForEach-Object {

     IF ( (iex"`$Label$_.Text.Length") -ne 0 )
     {
        iex "`$Label$_.Visible = `$true"
        iex "`$TextBox$_.Visible = `$true"

        iex "`$TextBox$_.Text = 'Enter new name for ' + `$Label$_.Text"
     }
}