如何创建ForEach循环以通过多个变量Powershell

时间:2013-08-06 11:34:32

标签: powershell foreach

我遇到了ForEach循环的问题。我试图循环通过相同类型的多个变量只是增加不同。 我试图根据同一行中的Label是否有文本来更改TextBox文本。

这就是我为每个Label编写和IF语句的方法,但我正在寻找通过ForEach循环遍历每个块的方法。我总共有8个标签和文本框。

这是代码:(我相信你会弄明白我在追求:) :)

IF ( $Label1.Text.Length -ne 0 ) 
{ 
    $Label1.Visible = $true
    $TextBox1.Visible = $true

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

ForEach的例子

$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 )
     }
}

等...

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

2 个答案:

答案 0 :(得分:1)

尝试一下,我无法使用标签&文本框对象,但它可以更好地调整它:

 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"
     }
}

答案 1 :(得分:1)

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

 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 )
     }
}
相关问题