Powershell Forms refresh GUI - powershell

The script is a simple administration tool to indicate the status of three windows services and to toggle them.
Everything works fine but I don't get it done to implement the refreshment of the GUI.
I want to show up the related status in labels and to hide the non-clickable buttons. I was playing around so far with a timer, but the GUI still doesn't refresh..
#variables
$ums = get-service "UMS Server"
$mySQL = get-service "mySQL56"
$maria = get-service "MariaDB_10.1.21"
function OnApplicationLoad {
return $true
}
function OnApplicationExit {
$script:ExitCode = 0
}
function generateForm {
Add-Type -AssemblyName System.Windows.Forms
$UMSDatabaseadministration = New-Object system.Windows.Forms.Form
$UMSDatabaseadministration.Text = "UMS Database administration"
$UMSDatabaseadministration.TopMost = $true
$UMSDatabaseadministration.Width = 614
$UMSDatabaseadministration.Height = 316
$UMSDatabaseadministration.StartPosition = "CenterScreen"
$timer = New-Object System.Windows.Forms.Timer #$UMSDatabaseadministration
$timer.Interval = 1000 # once per second
$timer.Add_Tick({ $UMSDatabaseadministration.Refresh() })
#button 1 start UMS
$button11 = New-Object system.windows.Forms.Button
$button11.Text = "start"
$button11.Width = 60
$button11.Height = 30
if ($ums.Status -eq "Running"){
$button11.visible = $false
}
$button11.Add_Click({
$ums.start()
})
$button11.location = new-object system.drawing.point(303,38)
$button11.Font = "Microsoft Sans Serif,10"
$UMSDatabaseadministration.controls.Add($button11)
#button 2 stop UMS
$button15 = New-Object system.windows.Forms.Button
$button15.Text = "stop"
$button15.Width = 60
$button15.Height = 30
if ($ums.Status -eq "Stopped"){
$button15.visible = $false
}
$button15.Add_Click({$ums.stop()})
$button15.location = new-object system.drawing.point(409,39)
$button15.Font = "Microsoft Sans Serif,10"
$UMSDatabaseadministration.controls.Add($button15)
#button 3 start mySQL
$button12 = New-Object system.windows.Forms.Button
$button12.Text = "start"
$button12.Width = 60
$button12.Height = 30
if ($maria.Status -eq "Running" -Or $mySQL.Status -eq "Running"){
$button12.visible = $false
}
$button12.Add_Click({$mySQL.start()})
$button12.location = new-object system.drawing.point(303,98)
$button12.Font = "Microsoft Sans Serif,10"
$UMSDatabaseadministration.controls.Add($button12)
#button 4 stop mySQL
$button14 = New-Object system.windows.Forms.Button
$button14.Text = "stop"
$button14.Width = 60
$button14.Height = 30
if ($mySQL.Status -eq "Stopped"){
$button14.visible = $false
}
$button14.Add_Click({$mySQL.stop()})
$button14.location = new-object system.drawing.point(410,99)
$button14.Font = "Microsoft Sans Serif,10"
$UMSDatabaseadministration.controls.Add($button14)
#button 5 start mariaDB
$button13 = New-Object system.windows.Forms.Button
$button13.Text = "start"
$button13.Width = 60
$button13.Height = 30
if ($mySQL.Status -eq "Running" -Or $maria.Status -eq "Running"){
$button13.visible = $false
}
$button13.Add_Click({$maria.start()})
$button13.location = new-object system.drawing.point(302,147)
$button13.Font = "Microsoft Sans Serif,10"
$UMSDatabaseadministration.controls.Add($button13)
#button 6 stop mariaDB
$button16 = New-Object system.windows.Forms.Button
$button16.Text = "stop"
$button16.Width = 60
$button16.Height = 30
if ($maria.Status -eq "Stopped"){
$button16.visible = $false
}
$button16.Add_Click({$maria.stop()})
$button16.location = new-object system.drawing.point(410,148)
$button16.Font = "Microsoft Sans Serif,10"
$UMSDatabaseadministration.controls.Add($button16)
$button17 = New-Object system.windows.Forms.Button
$button17.Text = "shut down UMS Server and toggle DB`'s"
$button17.Add_Click({
#variables
$ums = get-service "UMS Server"
$mySQL = get-service "mySQL56"
$maria = get-service "MariaDB_10.1.21"
if ($ums.Status -eq "Running") {$ums.stop()}
if ($mySQL.Status -eq "Running") {$mySQL.stop(); $maria.start()}
if ($maria.Status -eq "Running") {$maria.stop(); $mySQL.start()}
})
$button17.Width = 166
$button17.Height = 42
$button17.location = new-object system.drawing.point(303,209)
$button17.Font = "Microsoft Sans Serif,10"
$UMSDatabaseadministration.controls.Add($button17)
$label18 = New-Object system.windows.Forms.Label
$label18.Text = "UMS Server is:"
$label18.AutoSize = $true
$label18.Width = 25
$label18.Height = 10
$label18.location = new-object system.drawing.point(33,38)
$label18.Font = "Microsoft Sans Serif,10"
$UMSDatabaseadministration.controls.Add($label18)
$label19 = New-Object system.windows.Forms.Label
$label19.Text = "mySQL is:"
$label19.AutoSize = $true
$label19.Width = 25
$label19.Height = 10
$label19.location = new-object system.drawing.point(33,95)
$label19.Font = "Microsoft Sans Serif,10"
$UMSDatabaseadministration.controls.Add($label19)
$label20 = New-Object system.windows.Forms.Label
$label20.Text = "mariaDB is:"
$label20.AutoSize = $true
$label20.Width = 25
$label20.Height = 10
$label20.location = new-object system.drawing.point(34,146)
$label20.Font = "Microsoft Sans Serif,10"
$UMSDatabaseadministration.controls.Add($label20)
#status UMS red
$label24 = New-Object system.windows.Forms.Label
$label24.Text = $ums.status
$label24.AutoSize = $true
$label24.ForeColor = "#fe0004"
$label24.Width = 25
$label24.Height = 10
if ($ums.status -eq "Running"){
$label24.visible = $false
}
$label24.location = new-object system.drawing.point(152,37)
$label24.Font = "Microsoft Sans Serif,10"
$UMSDatabaseadministration.controls.Add($label24)
#status UMS green
$label25 = New-Object system.windows.Forms.Label
$label25.Text = $ums.status
$label25.AutoSize = $true
$label25.ForeColor = "#149600"
$label25.Width = 25
$label25.Height = 10
if ($ums.status -eq "Stopped"){
$label25.visible = $false
}
$label25.location = new-object system.drawing.point(153,40)
$label25.Font = "Microsoft Sans Serif,10"
$UMSDatabaseadministration.controls.Add($label25)
#status mySQL red
$label26 = New-Object system.windows.Forms.Label
$label26.Text = $mySQL.status
$label26.AutoSize = $true
$label26.ForeColor = "#ff0004"
$label26.Width = 25
$label26.Height = 10
if ($mySQL.status -eq "Running"){
$label26.visible = $false
}
$label26.location = new-object system.drawing.point(152,94)
$label26.Font = "Microsoft Sans Serif,10"
$UMSDatabaseadministration.controls.Add($label26)
#status mySQL green
$label27 = New-Object system.windows.Forms.Label
$label27.Text = $mySQL.status
$label27.AutoSize = $true
$label27.ForeColor = "#149600"
$label27.Width = 25
$label27.Height = 10
if ($mySQL.status -eq "Stopped"){
$label27.visible = $false
}
$label27.location = new-object system.drawing.point(152,96)
$label27.Font = "Microsoft Sans Serif,10"
$UMSDatabaseadministration.controls.Add($label27)
#status mariaDB red
$label28 = New-Object system.windows.Forms.Label
$label28.Text = $maria.status
$label28.AutoSize = $true
$label28.ForeColor = "#ff0004"
$label28.Width = 25
$label28.Height = 10
if ($maria.status -eq "Running"){
$label28.visible = $false
}
$label28.location = new-object system.drawing.point(151,145)
$label28.Font = "Microsoft Sans Serif,10"
$UMSDatabaseadministration.controls.Add($label28)
#status mariaDB green
$label29 = New-Object system.windows.Forms.Label
$label29.Text = $maria.status
$label29.AutoSize = $true
$label29.ForeColor = "#149600"
$label29.Width = 25
$label29.Height = 10
if ($maria.status -eq "Stopped"){
$label29.visible = $false
}
$label29.location = new-object system.drawing.point(151,145)
$label29.Font = "Microsoft Sans Serif,10"
$UMSDatabaseadministration.controls.Add($label29)
[void]
$UMSDatabaseadministration.ShowDialog()
$UMSDatabaseadministration.Dispose()
}
if(OnApplicationLoad -eq $true)
{
GenerateForm | Out-Null
$timer.Start()
OnApplicationExit
}

First I must say that your code needs a lot of TLC. You shouldn't label your buttons or labels 1-20. Makes the code look messy and 15 days down the line you will have no idea what the code says. At lines 2-4 and 128-130 you define your variables twice.
What I have done now is create this Service GUI that will not just help you out, but anyone looking to do the same kind of task. You simple add the services you want into the Param function.
First we see if you are an Administrator, because not everyone is.
Add-Type -AssemblyName System.Windows.Forms
function Test-Admin {
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
if ((Test-Admin) -eq $false) {
if ($elevated)
{
# tried to elevate, did not work, aborting
}
else {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
}
exit
}
We create a central location to have the parameters.
Note that you see that I use the $Global: You can read about that here:
https://msdn.microsoft.com/en-us/powershell/reference/3.0/microsoft.powershell.core/about/about_scopes
Function Param{
$Global:Option1 = get-service "Hamachi2Svc"
$Global:Option2 = get-service "NitroUpdateService"
$Global:Option3 = get-service "TeamViewer"
$Global:Option1Txt=$Global:Option1.Displayname
$Global:Option2Txt=$Global:Option2.Displayname
$Global:Option3Txt=$Global:Option3.Displayname
}
Now we create the Form
Function ServiceAdminForm {
$Form.Close()
$Form.Dispose()
Test-Admin
MakeForm
}
Now we define the functions that our buttons will use.
Function Option1 {
if ($Global:Option1.Status -eq "Running"){ Stop-Service $Global:Option1
}
else {Start-Service $Global:Option1}
}
Function Option2 {
if ($Global:Option2.Status -eq "Running"){ Stop-Service $Global:Option2
}
else {Start-Service $Global:Option2}
}
Function Option3 {
if ($Global:Option3.Status -eq "Running"){ Stop-Service $Global:Option3
}
else {Start-Service $Global:Option3}
}
Function Toggle {
if ($Global:Option1.Status -eq "Running") {$Global:Option1.stop()}
if ($Global:Option2.Status -eq "Running") {$Global:Option2.stop(); $Global:Option3.start()}
if ($Global:Option3.Status -eq "Running") {$Global:Option3.stop(); $Global:Option2.start()}
}
Now we make the layout of the GUI
Calling the parameters and the button functions.
Function MakeForm {
Param
$script:Form = New-Object system.Windows.Forms.Form
$Form.Text = "Service Administration"
$Font = New-Object System.Drawing.Font("Times New Roman",12,[System.Drawing.FontStyle]::Bold)
$Form.Font = $Font
#Label for Option1
$Global:Option1lbl = New-Object system.windows.Forms.Label
$Global:Option1lbl.Text = $Global:Option1.Status
$Global:Option1lbl.AutoSize = $true
$Global:Option1lbl.Width = 25
$Global:Option1lbl.Height = 10
$Global:Option1lbl.location = new-object system.drawing.point(5,90)
#Label for Option2
$Global:Option2lbl = New-Object system.windows.Forms.Label
$Global:Option2lbl.Text = $Global:Option2.Status
$Global:Option2lbl.AutoSize = $true
$Global:Option2lbl.Width = 25
$Global:Option2lbl.Height = 10
$Global:Option2lbl.location = new-object system.drawing.point(5,150)
#Label for Option3
$Global:Option3lbl = New-Object system.windows.Forms.Label
$Global:Option3lbl.Text = $Global:Option3.Status
$Global:Option3lbl.AutoSize = $true
$Global:Option3lbl.Width = 25
$Global:Option3lbl.Height = 10
$Global:Option3lbl.location = new-object system.drawing.point(5,210)
#Refresh/Reload
$Reloadbtn = New-Object System.Windows.Forms.Button
$Reloadbtn.Location = New-Object System.Drawing.Size(5,10)
$Reloadbtn.AutoSize = $true
$Reloadbtn.Text = "Reload"
$Reloadbtn.Add_Click({ServiceAdminForm})
#Toggle
$Togglebtn = New-Object System.Windows.Forms.Button
$Togglebtn.Location = New-Object System.Drawing.Size(80,10)
$Togglebtn.AutoSize = $true
$Togglebtn.Text = "Toggle"
$Togglebtn.Add_Click({Toggle})
#Button Option1
$Global:Option1btn = New-Object System.Windows.Forms.Button
$Global:Option1btn.Location = New-Object System.Drawing.Size(5,60)
$Global:Option1btn.AutoSize = $true
$Global:Option1btn.Text = "$Global:Option1Txt"
$Global:Option1btn.Add_Click({Option1})
#Button Option2
$Global:Option2btn = New-Object System.Windows.Forms.Button
$Global:Option2btn.Location = New-Object System.Drawing.Size(5,120)
$Global:Option2btn.AutoSize = $true
$Global:Option2btn.Text = "$Global:Option2Txt"
$Global:Option2btn.Add_Click({Option2})
#Button Option3
$Global:Option3btn = New-Object System.Windows.Forms.Button
$Global:Option3btn.Location = New-Object System.Drawing.Size(5,180)
$Global:Option3btn.AutoSize = $true
$Global:Option3btn.Text = "$Global:Option3Txt"
$Global:Option3btn.Add_Click({Option3})
#Form Controls
$Form.Controls.Add($Global:Option1lbl)
$Form.Controls.Add($Global:Option2lbl)
$Form.Controls.Add($Global:Option3lbl)
$Form.Controls.Add($Reloadbtn)
$Form.Controls.Add($Togglebtn)
$Form.Controls.Add($Global:Option1btn)
$Form.Controls.Add($Global:Option2btn)
$Form.Controls.Add($Global:Option3btn)
$Form.ShowDialog()
}
MakeForm
Maybe someone has a better way to refresh, but reloading the form does the job.

Related

Trying to modify powershell to include combobox to populate listbox

I have a working script that has a single printserver name hard coded into it which populates a listbox. you can click on a printer and click install it and then click to make it the default printer. This works fine but I would like to have a dropdown menu that contains several printservers. when a printserver is chosen from the list it would populate the listbox with all of the printers on that printserver. I have fried everything I can think of to make this work. what am I not getting right Below are the 2 sets of code. Working one first.
Working Code
### Variables
#Printserver
$printserver = "Myprintserver"
### Hide PowerShell Console
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'
$consolePtr = [Console.Window]::GetConsoleWindow()
[Console.Window]::ShowWindow($consolePtr, 0)
### GUI
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$Form.ClientSize = '350,237'
$Form.text = "Printer Install Tool"
$Form.TopMost = $false
$btn_Cancel = New-Object system.Windows.Forms.Button
$btn_Cancel.text = "Close"
$btn_Cancel.width = 110
$btn_Cancel.height = 30
$btn_Cancel.location = New-Object System.Drawing.Point(202,181)
$btn_Cancel.Font = 'Microsoft Sans Serif,10'
$btn_Install = New-Object system.Windows.Forms.Button
$btn_Install.text = "Install printer"
$btn_Install.width = 110
$btn_Install.height = 30
$btn_Install.location = New-Object System.Drawing.Point(202,101)
$btn_Install.Font = 'Microsoft Sans Serif,10'
$btn_Default = New-Object system.Windows.Forms.Button
$btn_Default.text = "Set as Default"
$btn_Default.width = 110
$btn_Default.height = 30
$btn_Default.location = New-Object System.Drawing.Point(202,141)
$btn_Default.Font = 'Microsoft Sans Serif,10'
$txtBox_Location = New-Object system.Windows.Forms.TextBox
$txtBox_Location.multiline = $false
$txtBox_Location.width = 147
$txtBox_Location.height = 20
$txtBox_Location.location = New-Object System.Drawing.Point(179,35)
$txtBox_Location.Font = 'Microsoft Sans Serif,8'
$listBox_Printers = New-Object system.Windows.Forms.ListBox
$listBox_Printers.text = "listBox"
$listBox_Printers.width = 159
$listBox_Printers.height = 192
$listBox_Printers.location = New-Object System.Drawing.Point(11,35)
$lbl_ChoosePrinter = New-Object system.Windows.Forms.Label
$lbl_ChoosePrinter.text = "Choose a printer"
$lbl_ChoosePrinter.AutoSize = $true
$lbl_ChoosePrinter.width = 25
$lbl_ChoosePrinter.height = 10
$lbl_ChoosePrinter.location = New-Object System.Drawing.Point(11,16)
$lbl_ChoosePrinter.Font = 'Microsoft Sans Serif,10'
$lbl_PrinterLoc = New-Object system.Windows.Forms.Label
$lbl_PrinterLoc.text = "Printer location"
$lbl_PrinterLoc.AutoSize = $true
$lbl_PrinterLoc.width = 25
$lbl_PrinterLoc.height = 10
$lbl_PrinterLoc.location = New-Object System.Drawing.Point(179,16)
$lbl_PrinterLoc.Font = 'Microsoft Sans Serif,10'
$Form.controls.AddRange(#($btn_Cancel,$btn_Install,$txtBox_Location,$listBox_Printers,$lbl_ChoosePrinter,$lbl_PrinterLoc,$btn_Default))
### Eventhandlers
$listBox_Printers.Add_SelectedIndexChanged({
$printName = $listBox_Printers.SelectedItem
#write-host $printName
$txtBox_Location.Text = Get-Printer -ComputerName $printserver -Name $printName | Select-Object -ExpandProperty "Location"
})
$btn_Default.Add_Click({
$printName = $listBox_Printers.SelectedItem
(New-Object -ComObject WScript.Network).SetDefaultPrinter("\\$printserver\$printName")
})
$btn_Cancel.Add_Click({
$Form.Close()
})
$btn_Install.Add_Click({
$printName = $listBox_Printers.SelectedItem
get-wmiobject -class win32_printer -computer $printserver
rundll32 printui.dll,PrintUIEntry /in /n \\$printserver\$printName
})
### Main
$printName = $listBox_Printers.SelectedItem
$printers = Get-Printer -ComputerName $printserver | Select-Object -Property "Location", "Name"
foreach($printer in $printers){
$listBox_Printers.Items.Add($printer.Name)
}
[void]$Form.ShowDialog()
Non working code
### Variables
#Printserver
$printserver = "$cmbx_Server.SelectedItem"
### Hide PowerShell Console
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'
$consolePtr = [Console.Window]::GetConsoleWindow()
[Console.Window]::ShowWindow($consolePtr, 0)
### GUI
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$Form.ClientSize = '350,450'
$Form.text = "Printer Install Tool"
$Form.TopMost = $false
$lbl_Server = New-Object system.Windows.Forms.Label
$lbl_Server.text = "Print Server"
$lbl_Server.AutoSize = $true
$lbl_Server.width = 25
$lbl_Server.height = 10
$lbl_Server.location = New-Object System.Drawing.Point(11,16)
$lbl_Server.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$cmbx_Server = New-Object system.Windows.Forms.ComboBox
$cmbx_Server.text = "Choose Server"
$cmbx_Server.width = 100
$cmbx_Server.height = 30
#('Printserver1','Printserver2','Printserver3','Printserver3','Printserver4','Printserver5','Printserver6','Printserver7','Printserver8','Printserver9','Printserver0') | ForEach-Object {[void] $cmbx_Server.Items.Add($_)}
$cmbx_Server.location = New-Object System.Drawing.Point(6,46)
$cmbx_Server.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$btn_Server = New-Object system.Windows.Forms.Button
$btn_Server.text = "Select Server"
$btn_Server.width = 150
$btn_Server.height = 30
$btn_Server.location = New-Object System.Drawing.Point(110,46)
$btn_Server.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$btn_Cancel = New-Object system.Windows.Forms.Button
$btn_Cancel.text = "Close"
$btn_Cancel.width = 100
$btn_Cancel.height = 30
$btn_Cancel.location = New-Object System.Drawing.Point(225,410)
$btn_Cancel.Font = 'Microsoft Sans Serif,10'
$btn_Install = New-Object system.Windows.Forms.Button
$btn_Install.text = "Install printer"
$btn_Install.width = 100
$btn_Install.height = 30
$btn_Install.location = New-Object System.Drawing.Point(10,410)
$btn_Install.Font = 'Microsoft Sans Serif,10'
$btn_Default = New-Object system.Windows.Forms.Button
$btn_Default.text = "Set as Default"
$btn_Default.width = 100
$btn_Default.height = 30
$btn_Default.location = New-Object System.Drawing.Point(117,410)
$btn_Default.Font = 'Microsoft Sans Serif,10'
$txtBox_Location = New-Object system.Windows.Forms.TextBox
$txtBox_Location.multiline = $false
$txtBox_Location.width = 147
$txtBox_Location.height = 20
$txtBox_Location.location = New-Object System.Drawing.Point(179,110)
$txtBox_Location.Font = 'Microsoft Sans Serif,8'
$listBox_Printers = New-Object system.Windows.Forms.ListBox
$listBox_Printers.text = "listBox"
$listBox_Printers.width = 159
$listBox_Printers.height = 192
$listBox_Printers.location = New-Object System.Drawing.Point(11,110)
$lbl_ChoosePrinter = New-Object system.Windows.Forms.Label
$lbl_ChoosePrinter.text = "Choose a printer"
$lbl_ChoosePrinter.AutoSize = $true
$lbl_ChoosePrinter.width = 25
$lbl_ChoosePrinter.height = 10
$lbl_ChoosePrinter.location = New-Object System.Drawing.Point(11,90)
$lbl_ChoosePrinter.Font = 'Microsoft Sans Serif,10'
$lbl_PrinterLoc = New-Object system.Windows.Forms.Label
$lbl_PrinterLoc.text = "Printer location"
$lbl_PrinterLoc.AutoSize = $true
$lbl_PrinterLoc.width = 25
$lbl_PrinterLoc.height = 10
$lbl_PrinterLoc.location = New-Object System.Drawing.Point(179,90)
$lbl_PrinterLoc.Font = 'Microsoft Sans Serif,10'
$Form.controls.AddRange(#($btn_Cancel,$btn_Install,$txtBox_Location,$listBox_Printers,$lbl_ChoosePrinter,$lbl_PrinterLoc,$btn_Default,$lbl_Server,$cmbx_Server,$btn_Server))
### Eventhandlers
$cmbx_Server.Add_SelectedIndexChanged({
write-host $cmbx_Server.text
})
$listBox_Printers.Add_SelectedIndexChanged({
$printName = $listBox_Printers.SelectedItem
#write-host $printName
$txtBox_Location.Text = Get-Printer -ComputerName $printserver -Name $printName | Select-Object -ExpandProperty "Location"
})
$btn_Default.Add_Click({
Get-PSDrive
Set-Location 'HKCU:\Software\Microsoft\Windows NT\CurrentVersion\Windows'
Get-ItemProperty -path .
Set-ItemProperty -path . -name "LegacyDefaultPrinterMode" -value 1
c:
$printName = $listBox_Printers.SelectedItem
(New-Object -ComObject WScript.Network).SetDefaultPrinter("\\$printserver\$printName")
})
$btn_Server.Add_Click({$listBox_Printers.Text = $cmbx_Server.SelectedItem("Get-printer -Computername $printserver")})
#})
$btn_Cancel.Add_Click({
$Form.Close()
})
$btn_Install.Add_Click({
$printName = $listBox_Printers.SelectedItem
#get-wmiobject -class win32_printer -computer $printserver
#rundll32 printui.dll,PrintUIEntry /in /n \\$printserver\$printName
Add-Printer -ConnectionName \\$printServer\$printName
})
### Main
$printName = $listBox_Printers.SelectedItem
$printers = Get-Printer -ComputerName $printserver | Select-Object -Property "Location", "Name"
foreach($printer in $cmbx_Server.SelectedItem){
$listBox_Printers.Items.Add($printer.Name)
}
[void]$Form.ShowDialog()
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static ex`enter code here`tern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'
$consolePtr = [Console.Window]::GetConsoleWindow()
#[Console.Window]::ShowWindow($consolePtr, 0)
### GUI
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$Form.ClientSize = '700,450'
$Form.text = "Printer Installation Tool"
$Form.TopMost = $false
$cmbx_server = New-Object system.Windows.Forms.ComboBox
#$cmbx_server.text = "Printserver1"
$cmbx_server.width = 130
$cmbx_server.height = 20
#('Printserver1','Printserver2','Printserver3') | ForEach-Object {[void] $cmbx_server.Items.Add($_)}
$cmbx_server.location = New-Object System.Drawing.Point(11,59)
$cmbx_server.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$lbl_Server = New-Object system.Windows.Forms.Label
$lbl_Server.text = "Choose Server"
$lbl_Server.AutoSize = $true
$lbl_Server.width = 25
$lbl_Server.height = 10
$lbl_Server.location = New-Object System.Drawing.Point(11,16)
$lbl_Server.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$btn_Cancel = New-Object system.Windows.Forms.Button
$btn_Cancel.text = "Close"
$btn_Cancel.width = 110
$btn_Cancel.height = 30
$btn_Cancel.location = New-Object System.Drawing.Point(300,400)
$btn_Cancel.Font = 'Microsoft Sans Serif,10'
$btn_Install = New-Object system.Windows.Forms.Button
$btn_Install.text = "Install printer"
$btn_Install.width = 100
$btn_Install.height = 30
$btn_Install.location = New-Object System.Drawing.Point(11,310)
$btn_Install.Font = 'Microsoft Sans Serif,10'
$btn_Remove = New-Object system.Windows.Forms.Button
$btn_Remove.text = "Remove Printer"
$btn_Remove.width = 120
$btn_Remove.height = 30
$btn_Remove.location = New-Object System.Drawing.Point(375,310)
$btn_Remove.Font = 'Microsoft Sans Serif,10'
$lbl_Note = New-Object system.Windows.Forms.Label
$lbl_Note.text = "Note: Cannot remove Default Printer"
$lbl_Note.AutoSize = $true
$lbl_Note.width = 300
$lbl_Note.height = 10
$lbl_Note.location = New-Object System.Drawing.Point(350,340)
$lbl_Note.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$txtBox_Location = New-Object system.Windows.Forms.TextBox
$txtBox_Location.multiline = $false
$txtBox_Location.width = 147
$txtBox_Location.height = 20
$txtBox_Location.location = New-Object System.Drawing.Point(179,59)
$txtBox_Location.Font = 'Microsoft Sans Serif,8'
$listBox_Printers = New-Object system.Windows.Forms.ListBox
$listBox_Printers.text = ""
$listBox_Printers.width = 275
$listBox_Printers.height = 192
$listBox_Printers.location = New-Object System.Drawing.Point(11,120)
$listBox_Local_Printers = New-Object system.Windows.Forms.ListBox
$listBox_Local_Printers.text = ""
$listBox_Local_Printers.width = 310
$listBox_Local_Printers.height = 192
$listBox_Local_Printers.location = New-Object System.Drawing.Point(375,120)
$lbl_Local_Printer = New-Object system.Windows.Forms.Label
$lbl_Local_Printer.text = "Installed Printers"
$lbl_Local_Printer.AutoSize = $true
$lbl_Local_Printer.width = 25
$lbl_Local_Printer.height = 10
$lbl_Local_Printer.location = New-Object System.Drawing.Point(400,95)
$lbl_Local_Printer.Font = 'Microsoft Sans Serif,10'
$lbl_ChoosePrinter = New-Object system.Windows.Forms.Label
$lbl_ChoosePrinter.text = "Available Network Printers"
$lbl_ChoosePrinter.AutoSize = $true
$lbl_ChoosePrinter.width = 25
$lbl_ChoosePrinter.height = 10
$lbl_ChoosePrinter.location = New-Object System.Drawing.Point(11,95)
$lbl_ChoosePrinter.Font = 'Microsoft Sans Serif,10'
$lbl_PrinterLoc = New-Object system.Windows.Forms.Label
$lbl_PrinterLoc.text = "Printer location"
$lbl_PrinterLoc.AutoSize = $true
$lbl_PrinterLoc.width = 25
$lbl_PrinterLoc.height = 10
$lbl_PrinterLoc.location = New-Object System.Drawing.Point(179,16)
$lbl_PrinterLoc.Font = 'Microsoft Sans Serif,10'
### Set as Default Button
$btn_Default = New-Object system.Windows.Forms.Button
$btn_Default.text = "Set as Default"
$btn_Default.AutoSize = $false
$btn_Default.width = 110
$btn_Default.height = 30
$btn_Default.location = New-Object System.Drawing.Point(575,310)
$btn_Default.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
### Refresh button
$btn_Refresh = New-Object system.Windows.Forms.Button
$btn_Refresh.text = "Refresh"
$btn_Refresh.AutoSize = $false
$btn_Refresh.width = 80
$btn_Refresh.height = 30
$btn_Refresh.location = New-Object System.Drawing.Point(495,310)
$btn_Refresh.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Form.controls.AddRange(#($lbl_Note, $btn_Remove, $btn_Refresh, $btn_Cancel,$btn_Install,$txtBox_Location,$listBox_Printers,$lbl_ChoosePrinter,$lbl_PrinterLoc,$cmbx_server,$lbl_server,$btn_Default,$listBox_Local_Printers,$lbl_Local_Printer))
### Eventhandlers
$cmbx_server.Add_SelectedValueChanged({
$global:printserver = $cmbx_server.Items[$cmbx_server.SelectedIndex]
DisplayPrinters
})
$listBox_Printers.Add_SelectedValueChanged({ $cmbx_Server
$printName = $listBox_Printers.SelectedItem
$txtBox_Location.Text = Get-Printer -ComputerName $global:printserver -Name $printName | Select-Object -ExpandProperty "Location"
})
$btn_Default.Add_Click({
$printName = $listBox_Local_Printers.SelectedItem
SetPrinterAsDefault $printName
})
$btn_Remove.Add_Click({
$printName = $listBox_Local_Printers.SelectedItem
Remove-Printer $printName
})
$btn_Refresh.Add_Click({
DisplayPrinters
})
$btn_Cancel.Add_Click({
$Form.Close()
})
$btn_Install.Add_Click({
$printName = $listBox_Printers.SelectedItem
Add-Printer -ConnectionName \\$global:printserver\$printName
#SetPrinterAsDefault \\$global:printserver\$printName
})
Function SetPrinterAsDefault($printName){
Set-ItemProperty -path "HKCU:\Software\Microsoft\Windows NT\CurrentVersion\Windows" -name "LegacyDefaultPrinterMode" -value 1
if($printName -like "*(Default Printer)"){
#Printer is already default
DisplayPrinters
return
}
$printInfo = Get-Printer $printName
if($printInfo -ne $null){
if($printInfo.Type -eq "Local"){
$printer = Get-CimInstance -Class Win32_Printer -Filter "Name='$printName'"
Invoke-CimMethod -InputObject $printer -MethodName SetDefaultPrinter
}
else{
(New-Object -ComObject WScript.Network).SetDefaultPrinter("$printName")
}
}
DisplayPrinters
}
Function DisplayPrinters(){
#Remove all old
$listBox_Printers.Items.Clear()
$listBox_local_Printers.Items.Clear()
$printers = Get-Printer -ComputerName $global:printserver | Select-Object -Property "Location", "Name"
foreach($printer in $printers){
$listBox_Printers.Items.Add($printer.Name) | Out-Null
}
$defaultPrinter = Get-WmiObject -Query " SELECT * FROM Win32_Printer WHERE Default=$true" | select -ExpandProperty name
$local_printers = Get-Printer | Select-Object Name
foreach($printer in $local_printers){
if($printer.Name -eq $defaultPrinter){
$printer.name = $printer.name + " (Default Printer)"
}
$listBox_local_Printers.Items.Add($printer.Name) | Out-Null
}
}
### Main
$cmbx_server.text = $cmbx_server.Items[0]
[void]$Form.ShowDialog()

powershell progressbar in groupbox GUI

I'm working on a script but for some reason my ProgressBar won't appear in my groupbox.
I tried a lot of different things (like making the groupbox trensparent) but nothing really work.
Here is my code 'simplified' with just the problematic parts.
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object System.Windows.Forms.Form
$Form.ClientSize = ‘345,160’
$Form.Text = " bug progressbar "
$Form.StartPosition = "CenterScreen"
#Functions
Function BDDchoice(){
$BDD = $args[0]
$Label2.Text = "it takes a few seconds"
$ProgressBarcheck = New-Object System.Windows.Forms.ProgressBar
$ProgressBarcheck.Location = New-Object System.Drawing.Point(230,49)
$ProgressBarcheck.Size = New-Object System.Drawing.Size(98, 23)
$ProgressBarcheck.Style = "Marquee"
$ProgressBarcheck.MarqueeAnimationSpeed = 20
$ButtonNEXT1.Hide()
$Form.Controls.Add($ProgressBarcheck);
$job1 ={
sleep 10
$bdd_min = $args[0]
echo $bdd_min
}
Start-Job -ScriptBlock $job1 -ArgumentList $BDD -Name bdd
do { [System.Windows.Forms.Application]::DoEvents() } until ((Get-Job -Name bdd).State -eq "Completed")
Wait-Job -Name bdd
$resultat = Receive-Job -Name bdd -Keep
Get-Job | Remove-Job -Force
$TextBoxBDD.text = $resultat
$ProgressBarcheck.Hide()
$ButtonNEXT1.Visible = $true
$Label2.Text = "BDD:"
}
#variables
$BDDXS = #('SCHEM1','SCHEM2','SCHEM3','SCHEM4')
$BDD1 = 'BDD1'
$BDD2 = 'BDD2'
$BDD3 = 'BDD3'
$BDD4 = 'BDD4'
$BDD = $null
#groupbox
$GroupBoxCREATE = New-Object System.Windows.Forms.GroupBox
$GroupBoxCREATE.Location = New-Object System.Drawing.Point(10,5)
$GroupBoxCREATE.Width = 325
$GroupBoxCREATE.Height = 150
$GroupBoxCREATE.Text = " Create "
#combobox ZONE
$comboBoxTRIG = New-Object System.Windows.Forms.ComboBox
$comboBoxTRIG.Location = New-Object System.Drawing.Point(25, 50)
$comboBoxTRIG.Size = New-Object System.Drawing.Size(200, 200)
foreach($BDDX in $BDDXS)
{
$comboBoxTRIG.Items.add($BDDX)
}
$comboBoxTRIG.Text = "REGION"
$comboBoxTRIG.AutoCompleteMode = "SuggestAppend"
$comboBoxTRIG.AutoCompleteSource = "ListItems"
$comboBoxTRIG.SelectedIndex ="0"
#butons
$ButtonNEXT1 = New-Object System.Windows.Forms.Button
$ButtonNEXT1.Location = New-Object System.Drawing.Point(230,49)
$ButtonNEXT1.Size = New-Object System.Drawing.Size(98, 23)
$ButtonNEXT1.Text = "OK"
$ButtonNEXT1.add_Click({
$zone = $comboBoxTRIG.SelectedItem.ToString()
if ($zone -like "SCHEM1"){
$BDD = $BDD1
}
if ($zone -like "SCHEM2") {
$BDD = $BDD2
}
if ($zone -like "SCHEM3") {
$BDD = $BDD3
}
if ($zone -like "SCHEM4") {
$BDD = $BDD4
}
BDDchoice($BDD)
})
#labels
$Label1 = New-Object System.Windows.Forms.Label
$Label1.Location = New-Object System.Drawing.Point(25,25)
$Label1.Text = "REGION :"
$Label2 = New-Object System.Windows.Forms.Label
$Label2.Location = New-Object System.Drawing.Point(25,80)
$label2.Width = 200
$Label2.Text = "BDD :"
#textbox
$TextBoxBDD = New-Object System.Windows.Forms.TextBox
$TextBoxBDD.Location = New-Object System.Drawing.Point(25,100)
$TextBoxBDD.Width = 200
$TextBoxBDD.ReadOnly = $true
$TextBoxBDD.Text = ""
$TextboxBDD.BackColor = "white"
#list form's butons/lists/combobox
$Form.Controls.AddRange(#($TextBoxBDD))
$Form.controls.AddRange(#($Label1,$Label2))
$Form.controls.AddRange(#($ButtonNEXT1))
$Form.controls.AddRange(#($comboBoxTRIG))
$Form.controls.AddRange(#($GroupBoxCREATE))
$Form.ShowDialog()
i'm interested in any idea.
My coworkers could not find anything but I must admit we are far from expert (i'm still learning and so are they).
$Form.Controls.Add($ProgressBarcheck);
It looks like you're adding Progress Bar to your form, NOT the groupbox. Add progress bar to groupbox then add groupbox to form.
$GroupBoxCREATE.Controls.Add($ProgressBarcheck);
$Form.Controls.Add($GroupBoxCREATE);

PowerShell form not displaying when screen is locked

I'm using a PowerShell form to prompt users to close down Adobe Reader so it can be upgraded. It's executed via SCCM, so runs in the System context. It works if the user is logged on and the session is active, but if the screen is locked, the form does not display when I unlock the screen, although the script is running.
I originally used $Form.ShowDialog() to display it but saw some other posts that said it wasn't reliable, so I switched to [void][System.Windows.Forms.Application]::Run($Form) but it still doesn't work. Can anyone help me fix this please?
Below is the trimmed-down script with only the code relevant to rendering the form.
Add-Type -AssemblyName System.Windows.Forms, System.Drawing
$Font = New-Object System.Drawing.Font('Segoe UI Light',14,[System.Drawing.FontStyle]::Regular)
$FontBold = New-Object System.Drawing.Font('Segoe UI',13,[System.Drawing.FontStyle]::Bold)
Function EndForm
{
$Timer.Stop();
$Timer.Dispose();
$Label.Dispose();
$CountdownLabel.Dispose();
$ProgressBar.Dispose();
$OKButton.Dispose();
$Form.Close();
$Form.Dispose();
}
$OnOKClick =
{
$MsgBoxInput = [System.Windows.Forms.MessageBox]::Show("Are you sure you want to close and uninstall Adobe Reader now?","Confirm Adobe Reader Removal","YesNo","Warning")
If ($MsgBoxInput -eq "Yes") {EndForm}
}
$Script:Countdown = 3600
$OKToolTip = "Click OK to close and uninstall Adobe Reader now"
$CountdownSubtitle = "Adobe Reader will close and uninstall in"
$Label = New-Object System.Windows.Forms.Label
$Label.AutoSize = $False
$Label.Height = 120
$Label.Width = 630
$Label.Font = $Font
$Label.BackColor = "White"
$Label.ForeColor = "#4D4C5C"
$Label.Location = New-Object System.Drawing.Size(52,180)
$Label.Text = "Your computer will soon be upgraded to newer versions of Windows 10 and Office 365. In order to succeed, the upgrade process requires that Adobe Reader be closed and uninstalled first. It will not be available for use again until after the upgrade has completed."
$CountdownLabel = New-Object System.Windows.Forms.Label
$CountdownLabel.AutoSize = $False
$CountdownLabel.Height = 40
$CountdownLabel.Width = 530
$CountdownLabel.Font = $Font
$CountdownLabel.BackColor = "White"
$CountdownLabel.ForeColor = "#4D4C5C"
$CountdownLabel.Location = New-Object System.Drawing.Size(120,380)
$ProgressBar = New-Object System.Windows.Forms.ProgressBar
$ProgressBar.Location = New-Object System.Drawing.Size(52,340)
$ProgressBar.Size = New-Object System.Drawing.Size(635,35)
$ProgressBar.Style = "Continuous"
$ProgressBar.Maximum = $Script:Countdown
$ProgressBar.Minimum = 0
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Name = "OK_Button"
$OKButton.Size = New-Object System.Drawing.Size(80,40)
$OKButton.Location = New-Object System.Drawing.Size(330,450)
$OKButton.UseVisualStyleBackColor = $True
$OKButton.Text = "OK"
$OKButton.DataBindings.DefaultDataSourceUpdateMode = 0
$OKButton.Add_Click($OnOKClick)
$ToolTip = New-Object System.Windows.Forms.ToolTip
$ToolTip.IsBalloon = $False
$ToolTip.InitialDelay = 100
$ToolTip.ReshowDelay = 200
$ToolTip.SetToolTip($OKButton,$OKToolTip)
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "Contoso LLC"
$Form.Font = $Font
$Form.Width = 770
$Form.Height = 580
$Form.MinimizeBox = $False
$Form.MaximizeBox = $False
$Form.ControlBox = $False
$Form.ShowIcon = $False
$Form.WindowState = "Normal"
$Form.FormBorderStyle = "Fixed3D"
$Form.ShowInTaskbar = $True
$Form.StartPosition = "CenterScreen"
$Form.Topmost = $True
$Form.Controls.Add($ProgressBar)
$Form.Controls.Add($Label)
$Form.Controls.Add($CountdownLabel)
$Form.Controls.Add($OKButton)
$Timer = New-Object System.Windows.Forms.Timer
$Timer.Interval = 1000
$Timer.Add_Tick(
{
If ($Script:Countdown -eq 0) {EndForm}
$ProgressBar.Value = $Script:Countdown
$TimeRemain = New-Timespan -Seconds $Script:Countdown
$HrsRemain = $TimeRemain.Hours
$MinsRemain = $TimeRemain.Minutes
$SecsRemain = $TimeRemain.Seconds
If ($HrsRemain -ge 2) {$HrsText = "$HrsRemain hours"}
If ($HrsRemain -eq 1) {$HrsText = "$HrsRemain hour"}
If ($MinsRemain -ge 2) {$MinsText = "$MinsRemain minutes"}
If ($MinsRemain -eq 1) {$MinsText = "$MinsRemain minute"}
If ($SecsRemain -ge 2) {$SecsText = "$SecsRemain seconds"}
If ($SecsRemain -eq 1) {$SecsText = "$SecsRemain second"}
$CountdownLabel.Text = "$CountdownSubtitle $HrsText $MinsText $SecsText"
If ($HrsRemain -ge 1 -And $MinsRemain -eq 0) {$CountdownLabel.Text = "$CountdownSubtitle $HrsText $SecsText"}
If ($HrsRemain -eq 0) {$CountdownLabel.Text = "$CountdownSubtitle $MinsText $SecsText"}
If ($HrsRemain -eq 0 -And $MinsRemain -eq 0) {$CountdownLabel.Text = "$CountdownSubtitle $SecsText"}
$Script:Countdown--
})
$Timer.Start()
[void][System.Windows.Forms.Application]::Run($Form)
I have decided to 'work around' this issue by detecting for the presence of the logonui process, which means the screen is locked. In that case, I will just close Adobe Reader anyway.

Prevent Powershell GUI from closing

I want to prevent my Powershell Form from closing after a submit button is pressed. After the function "search_PC" there is no more code and the form closes. I want to still be able to write stuff in there after the function is finished. I have already tried the pause function and while($true) loops. I would be very happy about an answer.
Import-Module ActiveDirectory
# Assembly for GUI
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# Create Form
$objForm = New-Object System.Windows.Forms.Form
$objForm.Size = New-Object System.Drawing.Size(400,500)
$objForm.Backcolor="white"
$objForm.StartPosition = "CenterScreen"
$objForm.Text = "Example Software"
$objForm.Icon="C:\Users\...\icon.ico"
# Label
$objLabel1 = New-Object System.Windows.Forms.Label
$objLabel1.Location = New-Object System.Drawing.Size(80,30)
$objLabel1.Size = New-Object System.Drawing.Size(60,20)
$objLabel1.Text = "UserID:"
$objForm.Controls.Add($objLabel1)
# Textbox
$objTextBox1 = New-Object System.Windows.Forms.TextBox
$objTextBox1.Location = New-Object System.Drawing.Size(160,28)
$objTextBox1.Size = New-Object System.Drawing.Size(100,20)
$objForm.Controls.Add($objTextBox1)
# Label
$objLabel2 = New-Object System.Windows.Forms.Label
$objLabel2.Location = New-Object System.Drawing.Size(80,72)
$objLabel2.Size = New-Object System.Drawing.Size(80,20)
$objLabel2.Text = "PC-Name:"
$objForm.Controls.Add($objLabel2)
# Textbox
$objTextBox2 = New-Object System.Windows.Forms.TextBox
$objTextBox2.Location = New-Object System.Drawing.Size(160,70)
$objTextBox2.Size = New-Object System.Drawing.Size(100,20)
$objForm.Controls.Add($objTextBox2)
# Button for closing
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(100,220)
$CancelButton.Size = New-Object System.Drawing.Size(163,25)
$CancelButton.Text = "Exit"
$CancelButton.Name = "Exit"
$CancelButton.DialogResult = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)
# Checkbox
$objTypeCheckbox1 = New-Object System.Windows.Forms.Checkbox
$objTypeCheckbox1.Location = New-Object System.Drawing.Size(80,120)
$objTypeCheckbox1.Size = New-Object System.Drawing.Size(500,20)
$objTypeCheckbox1.Text = "Internal Session Support"
$objTypeCheckbox1.TabIndex = 1
$objTypeCheckbox1.Add_Click({$objTypeCheckbox2.Checked = $false})
$objForm.Controls.Add($objTypeCheckbox1)
# Checkbox
$objTypeCheckbox2 = New-Object System.Windows.Forms.Checkbox
$objTypeCheckbox2.Location = New-Object System.Drawing.Size(80,140)
$objTypeCheckbox2.Size = New-Object System.Drawing.Size(500,20)
$objTypeCheckbox2.Text = "Session Support Internal & external"
$objTypeCheckbox2.TabIndex = 2
$objTypeCheckbox2.Add_Click({$objTypeCheckbox1.Checked = $false})
$objForm.Controls.Add($objTypeCheckbox2)
# Button fo checking the User Input
$SubmitButton = New-Object System.Windows.Forms.Button
$SubmitButton.Location = New-Object System.Drawing.Size(100,190)
$SubmitButton.Size = New-Object System.Drawing.Size(163,25)
$SubmitButton.Text = "Submit"
$SubmitButton.Name = "Submit"
$SubmitButton.DialogResult = "OK"
$objForm.AcceptButton = $SubmitButton
$SubmitButton.Add_Click({
$User = $objTextBox1.Text
$PC = $objTextBox2.Text
# Check if all User Inputs are filled out
if ( !($User.trim()) -or !($PC.trim()) ) {
[void] [Windows.Forms.MessageBox]::Show("Please fill out every value!", "Error", [Windows.Forms.MessageBoxButtons]::ok, [Windows.Forms.MessageBoxIcon]::Warning)}
if($objTypeCheckbox1.checked -eq $true) {$Software = "Internal"}
elseif($objTypeCheckbox2.checked -eq $true) {$Software = "Internal&External"}
else {[void] [Windows.Forms.MessageBox]::Show("Please fill out every value!", "Error", [Windows.Forms.MessageBoxButtons]::ok, [Windows.Forms.MessageBoxIcon]::Warning)}
search_user
})
$objForm.Controls.Add($SubmitButton)
$statusBar1 = New-Object System.Windows.Forms.StatusBar
$objForm.controls.add($statusBar1)
function createFile
{
$Date = Get-Date -Format d.M.yyyy
$Time = (Get-Date).ToString(„HH:mm:ss“)
$Time2 = (Get-Date).ToString(„HH-mm-ss“)
$Date2 = Get-Date -Format yyyy-M-d;
$FileName = $Time2 + " " + $Date2
$wrapper = New-Object PSObject -Property #{ 1 = $Date; 2 = $Time; 3 = $User; 4 = $PC; 5 = $Software }
Export-Csv -InputObject $wrapper -Path C:\Users\...\$FileName.csv -NoTypeInformation
[void] [Windows.Forms.MessageBox]::Show("Successful!")
}
function search_user
{
if (#(Get-ADUser -Filter {SamAccountName -eq $User}).Count -eq 0) {
$objTextBox1.BackColor = "Red";
$statusBar1.Text = "Couldn't find user!"
$objForm.Dispose()
}
else{$objTextBox1.BackColor = "Green"
search_PC}
}
function search_PC
{
$Client = $PC
if (#(Get-ADComputer -Filter {DNSHostName -eq $Client}).Count -eq 0) {
$objTextBox2.BackColor = "Red";
$statusBar1.Text = "Couldn't find PC!"
$objForm.Dispose()
}
else{$objTextBox2.BackColor = "Green"
createFile}
}
$objForm.ShowDialog() #Showing Form and elements
Screenshot of the form:
This line is your problem:
$SubmitButton.DialogResult = "OK"
It should be:
$SubmitButton.DialogResult = [System.Windows.Forms.DialogResult]::None
Or just be removed.
DialogResult

getting database table to show in dataGridView in powershell

I am building a powershell gui application that pulls info from a database table that I need to monitor. I am having an issue getting that data into the datagridview. I can do it manually so it shows at least one entry but I need it to show the full table results. This is my 1st powershell GUI project.
add-type -AssemblyName System.Data.OracleClient
Function ShowJobsInQueue()
{
## To connect by Service Name
$ora_server = "dm01-scan.campsys.com"
$ora_user = "appuser"
$ora_pass = "hillary"
$ora_servicename = "dbcamp1_svc.campsys.com"
## by ServiceName
$connection = new-object system.data.oracleclient.oracleconnection("Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=$ora_server)(PORT=1521)) (CONNECT_DATA=(SERVICE_NAME=$ora_servicename)));User Id=$ora_user;Password=$ora_pass;")
$connection.open()
$query = "SELECT * FROM ASYNCJOB WHERE TRUNC(START_DATE)= TRUNC(SYSDATE) AND job_type <>15 and STATUS in ('1','2') ORDER BY ASYNCJOB_ID DESC"
$list_set = new-object system.data.dataset
#$array = New-Object System.Collections.ArrayList
#$array.AddRange($list_table)
#$dataGridView.DataSource = $array
$list_adapter = new-object system.data.oracleclient.oracledataadapter($query, $connection)
$list_adapter.Fill($list_set) | Out-Null
$list_table = new-object system.data.datatable
$list_table = $list_set.Tables[0]
$DBValues = $list_table
while($dataGridView.Rows.Count -lt $list_table.Count) {
$dataGridView.Rows.Add() | Out-Null
}
for ($i=0;$i -lt $list_table.Count ;$i++) {
$dataGridView.rows[$i].Cells[0].Value = $list_table[$i].Item("ASYNCJOB_ID")
}
$connection.close()
$form.refresh()
}
$OnLoadForm_UpdateGrid=
{
ShowJobsInQueue
}
########################################
Add-Type -AssemblyName System.Windows.Forms
$Form = New-Object system.Windows.Forms.Form
$Form.Text = "Report Monitor"
$Form.TopMost = $true
$Form.minimumSize = New-Object System.Drawing.Size(1024,750)
$Form.maximumSize = New-Object System.Drawing.Size(1024,750)
$dataGridView = New-Object System.Windows.Forms.DataGridView
$dataGridView.Size=New-Object System.Drawing.Size(1024,570)
$form.Controls.Add($dataGridView)
$buttonRefresh = New-Object system.windows.Forms.Button
$buttonRefresh.Text = "Refresh"
$buttonRefresh.Width = 65
$buttonRefresh.Height = 35
$buttonRefresh.Add_Click({
$Form.close()
})
$buttonRefresh.location = new-object system.drawing.point(338,600)
$buttonRefresh.Font = "Microsoft Sans Serif,10"
$Form.controls.Add($buttonRefresh)
$buttonExit = New-Object system.windows.Forms.Button
$buttonExit.Text = "Exit"
$buttonExit.Width = 65
$buttonExit.Height = 35
$buttonExit.Add_Click({
$Form.close()
})
$buttonExit.location = new-object system.drawing.point(500,600)
$buttonExit.Font = "Microsoft Sans Serif,10"
$Form.controls.Add($buttonExit)
#Create an unbound DataGridView by declaring a column count.
$dataGridView.ColumnCount = 6
$dataGridView.ColumnHeadersVisible = $true
#Set the column header names.
$dataGridView.Columns[0].Name = "Row#"
$dataGridView.Columns[1].Name = "ASYNCJOB_ID"
$dataGridView.Columns[2].Name = "USER_ID"
$dataGridView.Columns[3].Name = "START_DATE"
$dataGridView.Columns[4].Name = "END_DATE"
$dataGridView.Columns[5].Name = "STATUS"
#$dataGridView.Rows[0].Cells[0].Value = "Value1"
#$dataGridView.Rows[0].Cells[1].Value = "Value2"
#$dataGridView.Rows[0].Cells[2].Value = "Value3"
#$dataGridView.Rows.Add();
#############################################################
$buttonOn = New-Object system.windows.Forms.RadioButton
$buttonOn.Text = "On"
$buttonOn.Width = 65
$buttonOn.Height = 35
$buttonOn.Add_Click({
# create function to turn on auto mode
$Form.close()
})
$buttonOn.location = new-object system.drawing.point(920,600)
$buttonOn.Font = "Microsoft Sans Serif,10"
$Form.controls.Add($buttonOn)
## button off
$buttonOff = New-Object system.windows.Forms.RadioButton
$buttonOff.Text = "Off"
$buttonOff.Width = 65
$buttonOff.Height = 35
$buttonOff.Add_Click({
# create function to turn off auto mode
$Form.close()
})
$buttonOff.location = new-object system.drawing.point(870,600)
$buttonOff.Font = "Microsoft Sans Serif,10"
$Form.controls.Add($buttonOff)
## end button off
#### auto mode label
$Automode = New-Object system.windows.Forms.Label
$Automode.Text = "Auto Mode"
$Automode.Width = 25
$Automode.Height = 10
$Automode.AutoSize = $true
$Automode.location = new-object system.drawing.point(875,580)
$Automode.Font = "Microsoft Sans Serif,10"
$Form.controls.Add($Automode)
#### end label
#Add Form event
$form.add_Load($OnLoadForm_UpdateGrid)
[void]$Form.ShowDialog()
$Form.Dispose()
Here is an example how you could do it:
$DBValues = "Value1","Value2","Value3","Value4","Value5","Value6","Value7","Value8","Value9","Value10"
while($dataGridView.Rows.Count -lt $DBValues.Count) {
$dataGridView.Rows.Add() | Out-Null
}
for ($i=0;$i -lt $DBValues.Count ;$i++) {
$dataGridView.rows[$i].Cells[0].Value = $DBValues[$i]
}
In your case you should do something like that:
while($dataGridView.Rows.Count -lt $list_table.Rows.Count) {
$dataGridView.Rows.Add() | Out-Null
}
for ($i=0;$i -lt $list_table.Rows.Count ;$i++) {
$dataGridView.rows[$i].Cells[0].Value = $list_table.Rows[$i].Item("ASYNCJOB_ID")
}