Обновлено : в приведенном ниже примере я собираюсь использовать компьютеры из Active Directory, используя Import-Module ActiveDirectory
Чтобы добавить элементы к вашему listbox
с помощью многомерного массива, мы можем использовать Object
и NoteProperty
для добавления к listbox
Ex:
#This example I am grabbing all computers from AD with the OS of windows server -- all windows servers
Import-Module ActiveDirectory
#Using the Name property for reboot and the Description for the listbox... you can use a different attribute if you like
$Computers = Get-ADComputer -filter {OperatingSystem -like "Windows Server*" -and Enabled -eq $true} -Properties Name, Description, OperatingSystem | Select Name, Description, OperatingSystem
$listboxCollection =@()
foreach($Computer in $Computers)
{
$Object = New-Object Object
$Object | Add-Member -type NoteProperty -Name CompName -Value $Computer.Name
$Object | Add-Member -type NoteProperty -Name Values -Value $Computer.Description
#fill the $listboxCollection
$listboxCollection += $Object
}
#Add collection to the $listbox
$listBox.Items.AddRange($listboxCollection)
Если бы вы отображали здесь свою форму, все ваши записи показывались бы как System.Object
. Чтобы получить Decription
из каждой коллекции в $listboxCollection
, чтобы показать, мы должны сказать ему ValueMember
и DisplayMember
.
Ex:
#This is using the properties above to display the correct item
$listBox.ValueMember = "CompName"
$listBox.DisplayMember = "Values"
Сохраняя исходное сообщение, чтобы получить выбранный элемент listbox
на кнопке ОК, вам нужно будет поставить условие. Однако есть несколько различных способов обработки этого события.
Ex:
#show form as dialog
$result = $form.ShowDialog()
if($result = [System.Windows.Forms.DialogResult]::OK)
{
$selectedComputer = $listBox.SelectedItem.CompName
Restart-Computer -ComputerName $selectedComputer -Credential Get-Credential Domain\Username -Force
}
Переменная $selectedComputer
будет выбранным компьютером. Примечание. В этом примере ничего не проверяется, чтобы убедиться в правильности выбора.
Полное решение:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
#This example I am grabbing all computers from AD with the OS of windows server -- all windows servers
Import-Module ActiveDirectory
#Using the Name property for reboot and the Description for the listbox... you can use a different attribute if you like
$Computers = Get-ADComputer -filter {OperatingSystem -like "Windows Server*" -and Enabled -eq $true} -Properties Name, Description, OperatingSystem | Select Name, Description, OperatingSystem
$form = New-Object System.Windows.Forms.Form
$form.Text = 'Select a Computer'
$form.Size = New-Object System.Drawing.Size(300,200)
$form.StartPosition = 'CenterScreen'
$listBox = New-Object System.Windows.Forms.ListBox
$listBox.Location = New-Object System.Drawing.Point(10,40)
$listBox.Size = New-Object System.Drawing.Size(260,20)
$listBox.Height = 80
#create an empty collection to use later
$listboxCollection =@()
foreach($Computer in $Computers)
{
$Object = New-Object Object
$Object | Add-Member -type NoteProperty -Name CompName -Value $Computer.Name
$Object | Add-Member -type NoteProperty -Name Values -Value $Computer.Description
$listboxCollection += $Object
}
$listBox.Items.AddRange($listboxCollection)
#This is using the properties above to display the correct item
$listBox.ValueMember = "CompName"
$listBox.DisplayMember = "Values"
#add listbox to form
$form.Controls.Add($listBox)
#Ok Button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = 'OK'
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
#keep on top
$form.Topmost = $true
#show form as dialog
$result = $form.ShowDialog()
if($result = [System.Windows.Forms.DialogResult]::OK)
{
#this tells it to get the Name of the property and not just the Item
$selectedComputer = $listBox.SelectedItem.CompName
Restart-Computer -ComputerName $selectedComputer -Credential Get-Credential Domain\Username -Force
}
Примечание: если вы используете запрос Active Directory, все ваши компьютеры должны иметь атрибуты Name
и Description
(если, конечно, вы не планируете обрабатывать пустые / нулевые значения)