如何创建动态命名的.NET对象数组?

时间:2019-07-16 01:42:13

标签: winforms powershell

我正在尝试在PowerShell中制作基于GUI的脚本。这将读取一些内容,然后生成其中包含不同内容的图块(在本例中为System.Windows.Forms.Panel)。

我尝试创建一个数组,然后创建System.Windows.Forms.Panel对象,然后添加它们。这似乎只是用数组中的相同对象覆盖,因为它的名称相同。然后,我尝试动态命名该对象,希望它能产生不同的效果,但是它告诉我“一个名为“ panel1”的对象已经存在,等等...

这是我到目前为止的代码,希望它可以显示我要执行的操作:

for ($i = 1; $i -le $numpanels; $i++) {
    $currentPanel = ""

    # Test Panel
    $currentPanel = New-Object System.Windows.Forms.Panel
    $currentPanel.Size = New-Object System.Drawing.Size(100,100)
    $currentPanel.Location = New-Object System.Drawing.Size((10 + ($i * 100)),10)
    $currentPanel.BackColor = 'White'
    $currentPanel.Add_MouseUp({    
        $X = [System.Windows.Forms.Cursor]::Position.X
        $Y = [System.Windows.Forms.Cursor]::Position.Y

        $this.Location = New-Object System.Drawing.Size(($X - $Form.Location.X - 50),($Y - $Form.Location.Y - 50))
        Write-Host "End Location: $($X - $Form.Location.X) / $($Y - $Form.Location.Y)"
        $Form.Controls.Add($this)
    })
    $currentPanel.Add_MouseDown({
        Write-Host "Start Location: $($this.Location.X) / $($this.Location.Y)"
        $Form.Controls.Remove($this)
    })

    New-Variable -Name "panel$i" -Value $currentPanel

    $panels += Get-Variable -Name "panel$i"
}

我希望将一些面板(由$numpanels定义)添加到我的表单中,每个面板都有各自的属性。

它给出以下错误信息:

New-Variable : A variable with name 'panel1' already exists.
At \\server\script.ps1:74 char:5
+     New-Variable -Name "panel$i" -Value $currentPanel
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceExists: (panel1:String) [New-Variable], SessionStateException
    + FullyQualifiedErrorId : VariableAlreadyExists,Microsoft.PowerShell.Commands.NewVariableCommand

0 个答案:

没有答案