动态设置变量

时间:2018-08-23 10:21:26

标签: powershell variables dynamic

我想做的事情与此类似:

$Range = 1..4

foreach ($Entry in $Range) {
    $Button$Entry = New-Object System.Windows.Forms.Button
    $Button$Entry.Location = New-Object System.Drawing.Size("200","100")
    $Button$Entry.Size = New-Object System.Drawing.Size("200","100")
    $Button$Entry.Text = "Test $Entry"
}

但是,我希望这与以下内容类似,我只是想不出如何添加.Location.Size.Text

$Range = 1..4

foreach ($Entry in $Range) {
    New-Variable -Name $Button$Entry -Value New-Object System.Windows.Forms.Button
}

1 个答案:

答案 0 :(得分:3)

改为使用数组:

$Buttons = foreach ($Entry in 1..4)
{
  $Button = New-Object System.Windows.Forms.Button
  $Button.Location = New-Object System.Drawing.Size("200","100")
  $Button.Size = New-Object System.Drawing.Size("200","100")
  $Button.text = "Test $Entry"
  $Button
}

,然后按值-1引用条目:

# Button with text "Test 3"
$Buttons[2]