Powershell Cancel button Doesn't Call Function - powershell

I have script that creates pop-up with checkbox.
If checkbox is checked and OK is pressed, $districtArray[1] is True
BUT
If checkbox is checked and CANCEL is pressed, $districtArray[1] is ALSO True
I wish that CANCEL button will make entire $districtArray FALSE.
Hence I included function initArray when CANCEL is clicked
$CancelButton.Add_Click({initArray; $Form.Close()})
And here is entire script for reference
$i = $NULL
$districtArray = #()
$highestDistrict = 33
function initArray{
for ($i = 0; $i -lt $highestDistrict; $i++)
{
$script:districtArray += #($false)
}
}
function checkbox_test{
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
# Set the size of your form
$Form = New-Object System.Windows.Forms.Form
$Form.width = 500
$Form.height = 200
$Form.Text = ”Select District”
# Set the font of the text to be used within the form
$Font = New-Object System.Drawing.Font("Times New Roman",12)
$Form.Font = $Font
# create your checkbox
$checkbox1 = new-object System.Windows.Forms.checkbox
$checkbox1.Location = new-object System.Drawing.Size(30,30)
$checkbox1.Size = new-object System.Drawing.Size(250,50)
$checkbox1.Text = "01"
$checkbox1.Checked = $false
$Form.Controls.Add($checkbox1)
# Add an OK button
$OKButton = new-object System.Windows.Forms.Button
$OKButton.Location = new-object System.Drawing.Size(130,100)
$OKButton.Size = new-object System.Drawing.Size(100,40)
$OKButton.Text = "OK"
$OKButton.Add_Click({$Form.Close()})
$form.Controls.Add($OKButton)
#Add a cancel button
$CancelButton = new-object System.Windows.Forms.Button
$CancelButton.Location = new-object System.Drawing.Size(255,100)
$CancelButton.Size = new-object System.Drawing.Size(100,40)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({initArray; $Form.Close()})
$form.Controls.Add($CancelButton)
########### This is the important piece ##############
# #
# Do something when the state of the checkbox changes #
#######################################################
$checkbox1.Add_CheckStateChanged({
if ($checkbox1.Checked){$districtArray[1] = $true} })
# Activate the form
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
}
initArray
#Call the function
checkbox_test
write-host "Value of districtArray[1] is" $districtArray[1]

Related

How to return a SelectedItems value when listbox items are inside an "add_SelectedValueChanged" block

After selecting an option from the drop down list ($RCVROption), when choosing an option from the list provided ($listBox), the $listBox.SelectedItems values are always Null. How do I get those values to assign to variable $x
This is the script I tried, my goal is to have the text from $listBox.SelectedItems to be used as a value that represents a file name, so that when you select an option from the list, and click OK, it runs that file.
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()
$form = New-Object System.Windows.Forms.Form
$form.Text = 'DMP Receiver Tail'
$form.Size = New-Object System.Drawing.Size(400,300)
$form.StartPosition = 'CenterScreen'
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(115,220)
$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)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(190,220)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = 'Cancel'
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(60,20)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = 'Which Receiver Would You Like To Tail?:'
$form.Controls.Add($label)
$RCVROption = new-object System.Windows.Forms.combobox
$RCVROption.Location = new-object System.Drawing.Size(20,40)
$RCVROption.Size = new-object System.Drawing.Size(335,30)
[void] $RCVROption.Items.Add('Receiver 560')
[void] $RCVROption.Items.Add('Receiver 2560')
$RCVROption.tabIndex = '0'
$RCVROption.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList;
$RCVROption.add_SelectedValueChanged(
{
if($RCVROption.SelectedItem -eq 'Receiver 560')
{
$listBox = New-Object System.Windows.Forms.Listbox
$listBox.Location = New-Object System.Drawing.Point(40,100)
$listBox.Size = New-Object System.Drawing.Size(260,80)
$listBox.SelectionMode = 'MultiExtended'
[void] $listBox.Items.Add('DMP-560-Line1')
[void] $listBox.Items.Add('DMP-560-Line2')
[void] $listBox.Items.Add('DMP-560-Line3')
[void] $listBox.Items.Add('DMP-560-Line4')
[void] $listBox.Items.Add('DMP-560-Line5')
$form.Controls.Add($listBox)
}
ELSEIF($RCVROption.SelectedItem -eq 'Receiver 2560')
{
$listBox = New-Object System.Windows.Forms.Listbox
$listBox.Location = New-Object System.Drawing.Point(40,100)
$listBox.Size = New-Object System.Drawing.Size(260,80)
$listBox.SelectionMode = 'MultiExtended'
[void] $listBox.Items.Add('DMP-2560-Line1')
[void] $listBox.Items.Add('DMP-2560-Line2')
[void] $listBox.Items.Add('DMP-2560-Line3')
[void] $listBox.Items.Add('DMP-2560-Line4')
[void] $listBox.Items.Add('DMP-2560-Line5')
$form.Controls.Add($listBox)
}
}
)
$form.Controls.Add($RCVROption)
$form.Topmost = $true
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
$x = $listBox.SelectedItems
$Fpath = 'D:\Toolbar\On Call\DMP-Tail\' + $x + '.exe'
Start-process -filepath $FPath
$Fpath
}
Based on your code, I'm guessing you come from a C# background. PowerShell does something weird where it can normally reach outside of script block's scope {code in scriptblock} and use variables that already exist at the time the scriptblock is executed. But it can't easily create or add new variables in the parent/outer scope.
Your code is creating $listBox inside the $RCVROption.add_SelectedValueChanged({code in scriptblock}) event scriptblock, and adding it to the controls for the form, so it continues to exist in the form, but not at the global/script scope of the your code.
I've reworked your code in a format that I've been learning over the last year. Everything you had should still be there, only in a more condensed form. You don't have to use this format, but I personally really like it. How PowerShell converts things like "Cancel" into [System.Windows.Forms.DialogResult]::Cancel is a bit of a mistery to me, but this type of conversion seems very reliable.
This version of the code creates the $listBox prior to firing of the $RCVROption.add_SelectedValueChanged event, clears the items in $listBox, and then populates the ListBox with the new values. The values are in an array, and piped into the [void] $listBox.Items.Add($_) command, executing it once per item in the array.
using namespace System.Windows.Forms
using namespace System.Drawing
Set-StrictMode -Version 3.0
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[Application]::EnableVisualStyles()
$form = [Form]#{
Text = 'DMP Receiver Tail'
Size = "400,300"
StartPosition = 'CenterScreen'
Topmost = $true
}
$OKButton = [Button]#{
DialogResult = "OK"
Location = "115,220"
Size = "75,23"
Text = 'OK'
}
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
$CancelButton = [Button]#{
DialogResult = "Cancel"
Location = "190,220"
Size = "75,23"
Text = 'Cancel'
}
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
$label = [Label]#{
Location = "60,20"
Size = "280,20"
Text = 'Which Receiver Would You Like To Tail?:'
}
$form.Controls.Add($label)
$RCVROption = [ComboBox]#{
DropDownStyle = "DropDownList"
Location = "20,40"
Size = "335,30"
tabIndex = '0'
}
[void] $RCVROption.Items.Add('Receiver 560')
[void] $RCVROption.Items.Add('Receiver 2560')
$listBox = [Listbox]#{
Location = "40,100"
SelectionMode = 'MultiExtended'
Size = "260,80"
}
$form.Controls.Add($listBox)
$RCVROption.add_SelectedValueChanged({
if($RCVROption.SelectedItem -eq 'Receiver 560') {
$listBox.Items.Clear()
'DMP-560-Line1', 'DMP-560-Line2', 'DMP-560-Line3', 'DMP-560-Line4', 'DMP-560-Line5' | ForEach-Object {
[void] $listBox.Items.Add($_)
}
}
elseif($RCVROption.SelectedItem -eq 'Receiver 2560') {
$listBox.Items.Clear()
'DMP-2560-Line1', 'DMP-2560-Line2', 'DMP-2560-Line3', 'DMP-2560-Line4', 'DMP-2560-Line5' | ForEach-Object {
[void] $listBox.Items.Add($_)
}
}
})
$form.Controls.Add($RCVROption)
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK) {
$x = $listBox.SelectedItems
$Fpath = 'D:\Toolbar\On Call\DMP-Tail\' + $x + '.exe'
Start-process -filepath $FPath
$Fpath
}

get acl from folders with file open dialog

I have built a little gui for getting the acl permissions for folders. with the path button i want to specify the folder path with a folder browser dialog and with the permissions button i want to get the acl. unfortunately the permissions button don't work because it can't get the folder path from the get-folder function. what's wrong with the function?
#################################################### Functions #######################################################
$path = Function Get-Folder ($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")|Out-Null
$Ordnername = New-Object System.Windows.Forms.FolderBrowserDialog
$Ordnername.Description = "Ordner auswählen"
$Ordnername.rootfolder = "MyComputer"
if($Ordnername.ShowDialog() -eq "OK")
{
$Ordner += $Ordnername.SelectedPath
}
return $Ordner
}
############################################## GetPermissions function
function GetPermissions{
#$Folder = get-folder
$Result = (Get-ACL $path).access | Format-Table IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags | Out-string
$outputBox.Text = $Result
}
function Close{
$Form.Close()
}
###################### CREATING PS GUI TOOL #############################
#### Form settings #################################################################
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Form = New-Object System.Windows.Forms.Form
$Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle #modifies the window border
$Form.Text = "Folder Permissions"
$Form.Size = New-Object System.Drawing.Size(1120,330)
$Form.StartPosition = "CenterScreen" #loads the window in the center of the screen
$Form.BackgroundImageLayout = "Zoom"
$Form.MinimizeBox = $False
$Form.MaximizeBox = $False
$Form.WindowState = "Normal"
$Form.SizeGripStyle = "Hide"
$Icon = [system.drawing.icon]::ExtractAssociatedIcon($PSHOME + "\powershell.exe")
$Form.Icon = $Icon
#### Input window with "Folder Path" label ##########################################
#$InputBox = New-Object System.Windows.Forms.TextBox
#$InputBox.Location = New-Object System.Drawing.Size(10,50)
#$InputBox.Size = New-Object System.Drawing.Size(180,20)
#$Form.Controls.Add($InputBox)
#$Label2 = New-Object System.Windows.Forms.Label
#$Label2.Text = "Folder Path:"
#$Label2.AutoSize = $True
#$Label2.Location = New-Object System.Drawing.Size(15,30)
#$Form.Controls.Add($Label2)
#### Group boxes for buttons ########################################################
$groupBox = New-Object System.Windows.Forms.GroupBox
$groupBox.Location = New-Object System.Drawing.Size(10,95)
$groupBox.size = New-Object System.Drawing.Size(180,180)
$groupBox.text = "Controls:"
$Form.Controls.Add($groupBox)
###################### BUTTONS ##########################################################
#### Path ###################################################################
$Path = New-Object System.Windows.Forms.Button
$Path.Location = New-Object System.Drawing.Size(10,10)
$Path.Size = New-Object System.Drawing.Size(150,60)
$Path.Text = "Path"
$Path.Add_Click({Get-folder})
$Path.Cursor = [System.Windows.Forms.Cursors]::Hand
$Form.Controls.Add($Path)
#### Permissions ###################################################################
$Permissions = New-Object System.Windows.Forms.Button
$Permissions.Location = New-Object System.Drawing.Size(15,25)
$Permissions.Size = New-Object System.Drawing.Size(150,60)
$Permissions.Text = "Permissions"
$Permissions.Add_Click({GetPermissions})
$Permissions.Cursor = [System.Windows.Forms.Cursors]::Hand
$groupBox.Controls.Add($Permissions)
#### Close ###################################################################
$Close = New-Object System.Windows.Forms.Button
$Close.Location = New-Object System.Drawing.Size(15,100)
$Close.Size = New-Object System.Drawing.Size(150,60)
$Close.Text = "Close"
$Close.Add_Click({Close})
$Close.Cursor = [System.Windows.Forms.Cursors]::Hand
$groupBox.Controls.Add($Close)
###################### END BUTTONS ######################################################
#### Output Box Field ###############################################################
$outputBox = New-Object System.Windows.Forms.RichTextBox
$outputBox.Location = New-Object System.Drawing.Size(200,20)
$outputBox.Size = New-Object System.Drawing.Size(900,265)
$outputBox.Font = New-Object System.Drawing.Font("Consolas", 8 ,[System.Drawing.FontStyle]::Regular)
$outputBox.MultiLine = $True
$outputBox.ScrollBars = "Vertical"
$Form.Controls.Add($outputBox)
##############################################
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
The reason for that mainly has to do with scoping, plus you should not write the function as $path = Function ... making it a call to the function.
Also, $Ordner += $Ordnername.SelectedPath is wrong, because you have never defined what $Ordner is in the function.
Below a rewrite of your code where I took the liberty to change some variable names to make them more self-explanatory:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
###################### CREATING PS GUI TOOL #############################
# define your selected path variable and initialize to nothing
$SelectedPath = $null
#################################################### Functions #######################################################
function Get-Folder {
$Ordnername = New-Object System.Windows.Forms.FolderBrowserDialog
$Ordnername.Description = "Ordner auswählen"
$Ordnername.rootfolder = "MyComputer"
if($Ordnername.ShowDialog() -eq "OK") {
$script:SelectedPath = $Ordnername.SelectedPath # use script scoping here
$outputBox.Text = $script:SelectedPath
}
}
############################################## GetPermissions function
function Get-Permissions {
$outputBox.Text = '' # clear the textbox
if (-not [string]::IsNullOrWhiteSpace($script:SelectedPath)) {
$Result = (Get-ACL $script:SelectedPath).Access | # use script scoping here
Format-Table IdentityReference,FileSystemRights,AccessControlType,IsInherited,InheritanceFlags | Out-string
$outputBox.Text = $script:SelectedPath + "`r`n`r`n" + $Result
}
}
#### Form settings #################################################################
$Form = New-Object System.Windows.Forms.Form
$Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle #modifies the window border
$Form.Text = "Folder Permissions"
$Form.Size = New-Object System.Drawing.Size(1120,330)
$Form.StartPosition = "CenterScreen" #loads the window in the center of the screen
$Form.BackgroundImageLayout = "Zoom"
$Form.MinimizeBox = $False
$Form.MaximizeBox = $False
$Form.WindowState = "Normal"
$Form.SizeGripStyle = "Hide"
$Icon = [System.Drawing.Icon]::ExtractAssociatedIcon((Join-Path -Path $PSHOME -ChildPath 'powershell.exe'))
$Form.Icon = $Icon
#### Group boxes for buttons ########################################################
$groupBox = New-Object System.Windows.Forms.GroupBox
$groupBox.Location = New-Object System.Drawing.Size(10,95)
$groupBox.size = New-Object System.Drawing.Size(180,180)
$groupBox.text = "Controls:"
$Form.Controls.Add($groupBox)
###################### BUTTONS ##########################################################
#### Path button ###################################################################
$PathButton = New-Object System.Windows.Forms.Button
$PathButton.Location = New-Object System.Drawing.Size(10,10)
$PathButton.Size = New-Object System.Drawing.Size(150,60)
$PathButton.Text = "Path"
$PathButton.Cursor = [System.Windows.Forms.Cursors]::Hand
$PathButton.Add_Click({Get-Folder})
$Form.Controls.Add($PathButton)
#### Permissions button ###################################################################
$Permissions = New-Object System.Windows.Forms.Button
$Permissions.Location = New-Object System.Drawing.Size(15,25)
$Permissions.Size = New-Object System.Drawing.Size(150,60)
$Permissions.Text = "Permissions"
$Permissions.Cursor = [System.Windows.Forms.Cursors]::Hand
$Permissions.Add_Click({Get-Permissions})
$groupBox.Controls.Add($Permissions)
#### Close ###################################################################
$Close = New-Object System.Windows.Forms.Button
$Close.Location = New-Object System.Drawing.Size(15,100)
$Close.Size = New-Object System.Drawing.Size(150,60)
$Close.Text = "Close"
$Close.Cursor = [System.Windows.Forms.Cursors]::Hand
$Close.Add_Click({$Form.Close()})
$groupBox.Controls.Add($Close)
###################### END BUTTONS ######################################################
#### Output Box Field ###############################################################
$outputBox = New-Object System.Windows.Forms.RichTextBox
$outputBox.Location = New-Object System.Drawing.Size(200,20)
$outputBox.Size = New-Object System.Drawing.Size(900,265)
$outputBox.Font = New-Object System.Drawing.Font("Consolas", 8 ,[System.Drawing.FontStyle]::Regular)
$outputBox.MultiLine = $True
$outputBox.ScrollBars = "Vertical"
$Form.Controls.Add($outputBox)
##############################################
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
# destroy the form from memory
$Form.Dispose()

Powershell dialog box with countdown and option to press cancel?

I have been trying to create a Powershell script that performs the following
Shows a dialog box that an update is about to occur
Provide a countdown of say 30 seconds
During the countdown, a user can press "Cancel Update"
If the countdown expires and "Cancel Update" was not pressed, then update will occur
Right before the loop, the window shows if I call $Counter_Form.ShowDialog() and I can click the Cancel button. When clicking, the following should occur.
Window should close after pressing the button. This is correct.
$cancel should be set to $true to indicate that Cancel was pressed. However, it remains $false and this is incorrect. Why is this?
Now, for the problems in the while loop
The window refreshes to show the new delay, but I cannot click "Cancel Update" since it just shows an hourglass icon and seems to be frozen
Script
#Adjust delay here
$delay = 5
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Counter_Form = New-Object System.Windows.Forms.Form
$Counter_Form.Text = "Warning"
#Form size options
$Counter_Form.Width = 350
$Counter_Form.Height = 150
#Centers form on screen
$Counter_Form.StartPosition = "CenterScreen"
#Places form on top of everything else
$Counter_Form.TopMost = $true
$Counter_Label = New-Object System.Windows.Forms.Label
$Counter_Label2 = New-Object System.Windows.Forms.Label
#Label2's text
$Counter_Label2.Text = "Please save all your work"
#Labels size and position
$Counter_Label.AutoSize = $true
$Counter_Label.Location = New-Object System.Drawing.Point(50,60)
$Counter_Label2.AutoSize = $true
$Counter_Label2.Location = New-Object System.Drawing.Point(90,30)
$cancel = $false
$button1 = New-Object System.Windows.Forms.Button
$button1.Text = "Cancel Update";
$button1.Location = New-Object System.Drawing.Point(130,80)
$button1.Add_Click({ $Counter_Form.Close(); $cancel = $true})
$Counter_Form.Controls.Add($Counter_Label)
$Counter_Form.Controls.Add($Counter_Label2)
$Counter_Form.Controls.Add($button1)
#LOOP!
while ($delay -ge 0 -And $cancel -eq $false)
{
$Counter_Form.Show()
#Timer label's text
$Counter_Label.Text = "Update will occur in $($delay) seconds."
start-sleep 1
$delay -= 1
}
$Counter_Form.Close()
For the first question about $cancel not being updated to $true, it is a result of scope.
Add the script scope, with $script:cancel = $true. So that line of code should be:
$button1.Add_Click({ $Counter_Form.Close(); $script:cancel = $true})
I didn't find an exact solution to what I started. A pieced together some code from various sources and found the following worked. I'm posting it here in case it ends up helping someone:
function ShowMsg ($timeout, $message)
{
Add-Type -AssemblyName system.windows.forms
Add-Type -AssemblyName system.drawing
$form = New-Object System.Windows.Forms.Form
$form.Text = "Window Title"
$form.Size = New-Object System.Drawing.Size(300,300)
$form.StartPosition = 'CenterScreen'
$label = New-Object System.Windows.Forms.label
$label.Text = $message
$label.Size = New-Object System.Drawing.Size(280,205)
$form.Controls.Add($label)
#add button to form
$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(160,215)
$okButton.Size = New-Object System.Drawing.Size(100,23)
$okButton.Text = 'Cancel Update'
$okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $okButton
$form.Controls.Add($okButton)
$cancelButton = New-Object System.Windows.Forms.Button
$cancelButton.Location = New-Object System.Drawing.Point(40,215)
$cancelButton.Size = New-Object System.Drawing.Size(100,23)
$cancelButton.Text = 'Allow Update'
$cancelButton.DialogResult = [System.Windows.Forms.DialogResult]::CANCEL
$form.CancelButton = $cancelButton
$form.Controls.Add($cancelButton)
$timer = New-Object System.Windows.Forms.Timer
$timer.Interval = $timeout * 1000
$timer.add_tick({$form.Close()})
$timer.Start()
$form.Topmost = $true
$form.ShowDialog()
$form.Dispose()
}
Calling the function:
$timeout = 60 #seconds
$message_response = ShowMsg -timeout $timeout -message "Hello, update is happening"

Returning multiple values from multiple drop-downs in Powershell

I am a very new to powershell. I was tasked with creating a GUI that takes in several strings from multiple drop-downs and renames the computer according to those choices. I am testing it with two options, $FacilityInitials and $BuildingNumber. Powershell is returning only the $BuildingNumber choice.
I may be doing something wrong with returning? How should I do multiple return fuctions properly? Thank you! :)
I tried checking for typos.
#Edit This item to change the DropDown Values
[array]$DropDownArray1 = "LI", "BE", "HA"
# This Function Returns the Selected Value and Closes the Form
function Return-DropDown {
$script:Choice = $DropDown1.SelectedItem.ToString()
$Form.Close()
}
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form = New-Object System.Windows.Forms.Form
$Form.width = 350
$Form.height = 200
$Form.Text = ”Computer Renamer”
$DropDown1 = new-object System.Windows.Forms.ComboBox
$DropDown1.Location = new-object System.Drawing.Size(100,30)
$DropDown1.Size = new-object System.Drawing.Size(130,30)
ForEach ($Item in $DropDownArray1) {
[void] $DropDown1.Items.Add($Item)
}
$Form.Controls.Add($DropDown1)
$DropDown1Label = new-object System.Windows.Forms.Label
$DropDown1Label.Location = new-object System.Drawing.Size(10,30)
$DropDown1Label.size = new-object System.Drawing.Size(100,20)
$DropDown1Label.Text = "Facility Initials:"
$Form.Controls.Add($DropDown1Label)
################################################################################
#Edit This item to change the DropDown Values
[array]$DropDownArray2 = "01", "02", "03"
# This Function Returns the Selected Value and Closes the Form
function Return-DropDown {
$script:Choice2 = $DropDown2.SelectedItem.ToString()
$Form.Close()
}
$DropDown2 = new-object System.Windows.Forms.ComboBox
$DropDown2.Location = new-object System.Drawing.Size(100,60)
$DropDown2.Size = new-object System.Drawing.Size(130,30)
ForEach ($Item in $DropDownArray2) {
[void] $DropDown2.Items.Add($Item)
}
$Form.Controls.Add($DropDown2)
$DropDown2Label = new-object System.Windows.Forms.Label
$DropDown2Label.Location = new-object System.Drawing.Size(10,60)
$DropDown2Label.size = new-object System.Drawing.Size(100,20)
$DropDown2Label.Text = "Building Number:"
$Form.Controls.Add($DropDown2Label)
################################################################################
#Button
$Button = new-object System.Windows.Forms.Button
$Button.Location = new-object System.Drawing.Size(100,130)
$Button.Size = new-object System.Drawing.Size(150,20)
$Button.Text = "Rename Computer"
$Button.Add_Click({Return-DropDown})
$form.Controls.Add($Button)
################################################################################
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
$FacilityInitials = $Choice
$BuildingNumber = $Choice2
$newCompName = $FacilityInitials + "-" + $BuildingNumber
$AdminAcc = ""
#Add Restart and Force later
Rename-Computer -NewName $newCompName -DomainCredential $AdminAcc

Storing variable from listbox

I'm attempting to gather user input and store it using $contacttype later on in my script. Originally I was using a simple text input, however I'm now trying to use a listbox to get user input instead.
Originally I was doing this:
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$contacttype = [Microsoft.VisualBasic.Interaction]::InputBox("Enter the contact type", " ")
However, I'm now trying to use a listbox with something like:
$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
[void] $listBox.Items.Add("VPN")
[void] $listBox.Items.Add("Phone")
[void] $listBox.Items.Add("E-mail")
$form.Controls.Add($listBox)
$form.Topmost = $True
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
$x = $listBox.SelectedItem
$x
}
How do I make sure $contacttype is populated with the output from the selected listbox item?
Per your answer, you just need to make sure you return your result to the $contacttype variable. However the code you provided wasn't complete, it didn't include the part that initiated $form or add an OK button to trigger the ok result.
Here's a complete version that I've also moved in to a function to show how you could make this a little more reusable:
Function Invoke-ListForm {
Param(
[string[]] $ListItem
)
$Form = New-Object system.Windows.Forms.Form
$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
ForEach ($Item in $ListItem) {
[void] $listBox.Items.Add($Item)
}
$listBox.Add_Click({ $listBox.SelectedItem })
$Form.Controls.Add($listBox)
$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)
$Form.Topmost = $True
$Result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
$listBox.SelectedItem
}
}
$ContactType = Invoke-ListForm VPN,Phone,E-mail
$ContactType