Script bypass my for loop to search how many folder - powershell

So I create an app for my company when I went yesterday all work correctly and now I see my script block by the Anti-Virus and when I use my personal PC for work he passe my loop for
Get-ChildItem -Path $folderpath -Include $filetype -recurse |
ForEach-Object `
{
$Result ++
}
So this is a part of my code and this is bypassed
And the other loop it's for create an .xls file wher I add information from other .xls
Sorry for my English I'm Belgian
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
#region begin GUI{
$Form = New-Object system.Windows.Forms.Form
$Form.ClientSize = '400,400'
$Form.text = "Fichier Provision CP"
$Form.TopMost = $false
$Icon = New-Object system.drawing.icon ("C:\Users\KILLIAN\Desktop\SAMPLE\ico.ico")
$Form.Icon = $Icon
$ProgressBar1 = New-Object system.Windows.Forms.ProgressBar
$ProgressBar1.width = 230
$ProgressBar1.height = 10
$ProgressBar1.location = New-Object System.Drawing.Point(80,360)
$Label1 = New-Object system.Windows.Forms.Label
$Label1.text = ""
$Label1.AutoSize = $true
$Label1.width = 80
$Label1.height = 10
$Label1.location = New-Object System.Drawing.Point(230,330)
$Label1.Font = 'Microsoft Sans Serif,10'
$Button1 = New-Object system.Windows.Forms.Button
$Button1.text = "Entrer"
$Button1.width = 90
$Button1.height = 29
$Button1.location = New-Object System.Drawing.Point(151,282)
$Button1.Font = 'Microsoft Sans Serif,10'
$Label2 = New-Object system.Windows.Forms.Label
$Label2.text = "Mois de fin"
$Label2.AutoSize = $true
$Label2.width = 25
$Label2.height = 10
$Label2.location = New-Object System.Drawing.Point(15,100)
$Label2.Font = 'Microsoft Sans Serif,10'
$Label3 = New-Object system.Windows.Forms.Label
$Label3.text = "Nom du fichier"
$Label3.AutoSize = $true
$Label3.width = 25
$Label3.height = 10
$Label3.location = New-Object System.Drawing.Point(15,60)
$Label3.Font = 'Microsoft Sans Serif,10'
$Label4 = New-Object system.Windows.Forms.Label
$Label4.text = "Jour férié"
$Label4.AutoSize = $true
$Label4.width = 25
$Label4.height = 10
$Label4.location = New-Object System.Drawing.Point(15,140)
$Label4.Font = 'Microsoft Sans Serif,10'
$TextBox2 = New-Object system.Windows.Forms.TextBox
$TextBox2.multiline = $false
$TextBox2.width = 200
$TextBox2.height = 20
$TextBox2.location = New-Object System.Drawing.Point(145,100)
$TextBox2.Font = 'Microsoft Sans Serif,10'
$TextBox1 = New-Object system.Windows.Forms.TextBox
$TextBox1.multiline = $false
$TextBox1.width = 200
$TextBox1.height = 20
$TextBox1.location = New-Object System.Drawing.Point(145,60)
$TextBox1.Font = 'Microsoft Sans Serif,10'
$TextBox3 = New-Object system.Windows.Forms.TextBox
$TextBox3.multiline = $false
$TextBox3.width = 200
$TextBox3.height = 20
$TextBox3.location = New-Object System.Drawing.Point(145,140)
$TextBox3.Font = 'Microsoft Sans Serif,10'
$Form.controls.AddRange(#($ProgressBar1,$Label1,$Button1,$Label2,$Label3,$TextBox1,$TextBox2,$Label4,$TextBox3))
#Var of the code{
#C:\Users\student\Desktop\SAMPLE\*\Congé
#G:\LUXDIVISION\SDE\COLLABORATEURS\*\Congé
$folderpath = "C:\Users\KILLIAN\Desktop\SAMPLE\test\*\Congé"
$Exl = New-Object -ComObject "Excel.Application"
$Exl.Visible = $false
$Exl.DisplayAlerts = $false
$objExcel = new-object -comobject excel.application
$objExcel.Visible = $false
$filetype ="*xls"
$Result = 0
$Counter = 0
$xlContinuous = 1
$xlThick = 4
$xlInsideVertical = 11
$xlEdgeBottom = 9
$a = 1
#Calling function}
function monthnamev (){
$boolean = $false
if($month -eq 3){
$boolean = $True
}
elseif($month -eq 6){
$boolean = $true
}
elseif($month -eq 9){
$boolean = $true
}
elseif($month -eq 12){
$boolean = $true
}
return $boolean
}
function monthname (){
$boolean = $false
if($month -eq 3){
$namemonth = "Mars"
}
elseif($month -eq 6){
$namemonth = "Juin"
}
elseif($month -eq 9){
$namemonth = "Septembre"
}
elseif($month -eq 12){
$namemonth = "Décembre"
}
return $namemonth
}
function isNumeric ($x) {
try {
0 + $x | Out-Null
return $true
} catch {
return $false
}
}
#Write your logic code here
$Form.Add_Shown({
$Year = Get-Date -UFormat "%Y"
$date = Get-Date -UFormat "%m %Y"
$TextBox1.Text = "Provision CP FIN $date"
})
Get-ChildItem -Path $folderpath -Include $filetype -recurse |
ForEach-Object `
{
$Result ++
}
$Button1.Add_Click({
#Var for the textbox
$namews = $TextBox1.Text
$month = $TextBox2.Text
$pholiday = $TextBox3.Text
#Public holiday
if (isNumeric($pholiday) -eq $true){
monthname
if (-not (monthnamev)){
[System.Windows.MessageBox]::Show('Erreur vous avez entrer une valeur incorrecte!', 'Error !', 0, 16)
}
else{
#Create a new .xls
$objWorkbook = $objExcel.Workbooks.Add()
$objWorksheet = $objWorkbook.Worksheets.Item(1)
Get-ChildItem -Path $folderpath -Include $filetype -recurse |
ForEach-Object `
{
## -- Calculate The Percentage Completed
$Counter++
[Int]$Percentage = ($Counter/$Result)*100
$ProgressBar1.Value = $Percentage
$Form.Refresh()
$Label1.Text = "Encodage : $Counter/$Result"
#Open the Collab holiday .xls
$workbook = $Exl.workbooks.open($_.fullname)
#Copy the name of the employee
$workbook.sheets.item(1).activate()
$WorkbookTotal=$workbook.Worksheets.item(1)
$value = $WorkbookTotal.Cells.Item(2, 2)
$value.Text
$objWorksheet.Activate()
$objWorksheet.Cells.Item($a, 1) = $value
Write-Warning $value.text
#Search Solde of previous year
$lastsheet = $workbook.Worksheets|Select -Last 1
$lastsheet.Activate()
$FoundAS = $lastsheet.Cells.Find('Solde')
$RowAS =$FoundAS.Row
$ColumnAS = $FoundAS.Column
[int]$RowAS2 = $RowAS
[int]$ColumnAS2 = $ColumnAS
$ColumnAS2 ++
$value = $lastsheet.cells.item($RowAS2,$ColumnAS2)
if (isNumeric($value) -eq $true){
$objWorksheet.Activate()
$objWorksheet.Cells.Item($a, 2) = $value
}
else{
$value = 0
$objWorksheet.Activate()
$objWorksheet.Cells.Item($a, 2) = $value
}
#Search Holyday
$Found = $lastsheet.Cells.Find('Congés $Year')
$Row =$Found.Row
$Column = $Found.Column
[int]$Row2 = $Row
[int]$Column2 = $Column
$Column2 ++
#Search Total
$Foundto = $lastsheet.Cells.Find('Total')
$Rowto =$Foundto.Row
$Columnto = $Foundto.Column
[int]$Rowto2 = $Rowto
[int]$Columnto2 = $Columnto
$Columnto2 ++
#Search month
$FoundSolde = $lastsheet.Cells.Find((monthname))
$RowSolde =$FoundSolde.Row
$ColumnSolde = $FoundSolde.Column
[int]$RowSolde2 = $RowSolde
[int]$ColumnSolde2 = $ColumnSolde
$ColumnSolde2 = $ColumnSolde2 + 5
$Soldemois = $lastsheet.cells.item($RowSolde2,$ColumnSolde2)
[double]$Soldemois2 = $Soldemois.text
if (isNumeric($Soldemois2) -eq $true){
$objWorksheet.Activate()
}
else{
[double]$Soldemois2 = 0
$objWorksheet.Activate()
}
#Search the correct value
$SoldePre = $lastsheet.cells.item($RowAS2,$ColumnAS2)
$total = $lastsheet.cells.item($Rowto2,$Columnto2)
$Holiday = $lastsheet.cells.item($Row2,$Column2)
[double]$total2 = $total.text
[double]$SoldePre2 = $SoldePre.text
[double]$Holiday2 = $Holiday.text
Write-Warning "Solde Précedent : $SoldePre2"
Write-Warning "Solde du fin de mois : $Soldemois2"
Write-Warning "le total de congé : $total2"
Write-Warning ""
$objWorksheet.Activate()
$objWorksheet.Cells.Item($a, 2) = $SoldePre2
$objWorksheet.Cells.Item($a, 3) = "=($Holiday2/12) * $month"
$objWorksheet.Cells.Item($a, 4) = "=$total2 - $Soldemois2"
$cell2 = $objWorksheet.Cells.Item($a, 3)
$cell3 = $objWorksheet.Cells.Item($a, 4)
[double]$celld2 = $cell2.text
[double]$celld3 = $cell3.text
$objWorksheet.Cells.Item($a, 5) = "=($SoldePre2 + $celld2 - $celld3) + $pholiday"
$workbook.save()
$workbook.close()
$a ++
}
$objWorkbook.saveas("C:\Users\KILLIAN\Desktop\SAMPLE\$namews.xls")
$objWorkbook.close()
$objExcel.Quit()
$objExcel = $null
$Exl.Quit()
$Exl = $null
}
}
else{
[System.Windows.MessageBox]::Show('Le Jour Férié doit être un chiffre !!!', 'Jour Férié incorrect', 0, 16)
}
})
$Form.ShowDialog()
It's all of my code
Here is when I launch the debbuger
And this is when I execute the second step (I tap F10)
When I launch your line
And the line on the cmd

Related

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

Powershell Form Buttons only working on last tab

I'm trying to make a form that will enable/disable devices that can wake up Windows machine. The idea being that you move the devices your want enabled from one listbox to another, for each machine. I have Powershell forms tabs dynamically generated for each machine, along with "Add", "Remove", "Ok", and "Cancel" buttons on each tab. But whenever I run the code with real machines the "Add" & "Remove" buttons only move the selected devices on the last tab, not the first two. "Ok" & "Cancel" buttons work as intended on all tabs.
I'm suspecting something isn't getting uniquely assigned to each pair of "Add"/"Remove" buttons during the Foreach-Object loop, leaving only the last tab in the loop working, but I can't figure out what I'm missing.
Full Code:
$_ComputerList = #("Computer01","Computer02","Computer03")
$_HashComputerTable = #{}
$_HashFormTabTable = #{}
$_HashDevices = #{}
$_PotentialItems = #()
$_EnabledItems = #()
Foreach ($_Computer in $_ComputerList) {
$_HashComputerTable[$_Computer] = #(
$_PotentialDevicesList = [System.Collections.ArrayList]#(Invoke-Command -ComputerName $_Computer -ScriptBlock {powercfg /DEVICEQUERY wake_programmable} | Where {$_ -ne ""})
$_EnabledDevicesList = [System.Collections.ArrayList]#(Invoke-Command -ComputerName $_Computer -ScriptBlock {powercfg /devicequery wake_armed} | Where {$_ -ne ""} )
$_PotentialDevicesList = [System.Collections.ArrayList]#(Compare-Object -ReferenceObject $_PotentialDevicesList -DifferenceObject $_EnabledDevicesList | Select -ExpandProperty InputObject)
New-Object -TypeName PSObject -Property #{
PotentialDevices = $_PotentialDevicesList
EnabledDevices = $_EnabledDevicesList
}
)
}
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$FormSizeWidth = 985
$FormSizeHeight = 560
$Form.MinimumSize = "$FormSizeWidth,$FormSizeHeight"
$Form.MaximumSize = "$FormSizeWidth,$FormSizeHeight"
#$Form.ClientSize = "$FormSizeWidth,$FormSizeHeight"
$Form.FormBorderStyle = 'Fixed3D'
$Form.MaximizeBox = $false
$Form.text = "Form"
$Form.TopMost = $false
$TabBox = New-object System.Windows.Forms.TabControl
$TabBox.DataBindings.DefaultDataSourceUpdateMode = 0
$TabBox.Location = New-Object System.Drawing.size(5,5)
$TabBox.Name = "tabControl"
$TabBox.Width = $FormSizeWidth - 27
$TabBox.Height = $FormSizeHeight - 57
$TabBox.Anchor = "Top, Bottom, Left, Right"
$Form.Controls.Add($TabBox)
Foreach ($_Computer in $_ComputerList){
$_HashFormTabTable[$_Computer] = New-Object -TypeName PSObject -Property #{
Tab = New-Object System.Windows.Forms.TabPage
PotentialBox = New-Object system.Windows.Forms.ListBox
EnabledBox = New-Object system.Windows.Forms.ListBox
PotentialLabel = New-Object system.Windows.Forms.Label
EnabledLabel = New-Object system.Windows.Forms.Label
AddButton = New-Object system.Windows.Forms.Button
RemoveButton = New-Object system.Windows.Forms.Button
}
####Tab
$_HashFormTabTable[$_Computer].Tab.DataBindings.DefaultDataSourceUpdateMode = 0
$_HashFormTabTable[$_Computer].Tab.UseVisualStyleBackColor = $True
$_HashFormTabTable[$_Computer].Tab.Name = "$_Computer"
$_HashFormTabTable[$_Computer].Tab.Text = "$_Computer"
$TabBox.Controls.Add($_HashFormTabTable[$_Computer].Tab)
####PotentialBox
$_HashFormTabTable[$_Computer].PotentialBox.location = New-Object System.Drawing.Point(10,30)
$_HashFormTabTable[$_Computer].PotentialBox.Font = New-Object System.Drawing.Font("Lucida Console",10,[System.Drawing.FontStyle]::Regular)
$_HashFormTabTable[$_Computer].PotentialBox.text = "PotentialBox_" + "$_Computer"
$_HashFormTabTable[$_Computer].PotentialBox.width = 395
$_HashFormTabTable[$_Computer].PotentialBox.height = 440
$_HashFormTabTable[$_Computer].PotentialBox.SelectionMode = 'MultiExtended'
$_HashFormTabTable[$_Computer].Tab.Controls.Add($_HashFormTabTable[$_Computer].PotentialBox)
####EnabledBox
$_HashFormTabTable[$_Computer].EnabledBox.location = New-Object System.Drawing.Point(540,30)
$_HashFormTabTable[$_Computer].EnabledBox.Font = New-Object System.Drawing.Font("Lucida Console",10,[System.Drawing.FontStyle]::Regular)
$_HashFormTabTable[$_Computer].EnabledBox.text = "EnabledBox_" + "$_Computer"
$_HashFormTabTable[$_Computer].EnabledBox.width = 395
$_HashFormTabTable[$_Computer].EnabledBox.height = 440
$_HashFormTabTable[$_Computer].EnabledBox.SelectionMode = 'MultiExtended'
$_HashFormTabTable[$_Computer].Tab.Controls.Add($_HashFormTabTable[$_Computer].EnabledBox)
####PotentialLabel
$_HashFormTabTable[$_Computer].PotentialLabel.location = New-Object System.Drawing.Point(19,10)
$_HashFormTabTable[$_Computer].PotentialLabel.text = "Potential to Wake Device"
$_HashFormTabTable[$_Computer].PotentialLabel.AutoSize = $true
$_HashFormTabTable[$_Computer].PotentialLabel.width = 25
$_HashFormTabTable[$_Computer].PotentialLabel.height = 10
$_HashFormTabTable[$_Computer].PotentialLabel.Font = 'Microsoft Sans Serif,10'
$_HashFormTabTable[$_Computer].Tab.Controls.Add($_HashFormTabTable[$_Computer].PotentialLabel)
####EnabledLabel
$_HashFormTabTable[$_Computer].EnabledLabel.location = New-Object System.Drawing.Point(575,10)
$_HashFormTabTable[$_Computer].EnabledLabel.text = "Enabled to Wake Device"
$_HashFormTabTable[$_Computer].EnabledLabel.AutoSize = $true
$_HashFormTabTable[$_Computer].EnabledLabel.width = 25
$_HashFormTabTable[$_Computer].EnabledLabel.height = 10
$_HashFormTabTable[$_Computer].EnabledLabel.Font = 'Microsoft Sans Serif,10'
$_HashFormTabTable[$_Computer].Tab.Controls.Add($_HashFormTabTable[$_Computer].EnabledLabel)
####AddButton
$_HashFormTabTable[$_Computer].AddButton.Name = "AddButton_$_Computer"
$_HashFormTabTable[$_Computer].AddButton.location = New-Object System.Drawing.Point(440,140)
$_HashFormTabTable[$_Computer].AddButton.text = "-->"
$_HashFormTabTable[$_Computer].AddButton.width = 70
$_HashFormTabTable[$_Computer].AddButton.height = 30
$_HashFormTabTable[$_Computer].AddButton.Font = 'Microsoft Sans Serif,10'
$_HashFormTabTable[$_Computer].AddButton.Add_Click({
$_PotentialItems = #($_HashFormTabTable[$_Computer].PotentialBox.SelectedItems)
$_PotentialItems | Foreach{
$_HashFormTabTable[$_Computer].EnabledBox.Items.Add($_)
$_HashFormTabTable[$_Computer].PotentialBox.Items.Remove($_)
}
})
$_HashFormTabTable[$_Computer].Tab.Controls.Add($_HashFormTabTable[$_Computer].AddButton)
####RemoveButton
$_HashFormTabTable[$_Computer].RemoveButton.Name = "RemoveButton_$_Computer"
$_HashFormTabTable[$_Computer].RemoveButton.location = New-Object System.Drawing.Point(440,185)
$_HashFormTabTable[$_Computer].RemoveButton.text = "<--"
$_HashFormTabTable[$_Computer].RemoveButton.width = 70
$_HashFormTabTable[$_Computer].RemoveButton.height = 30
$_HashFormTabTable[$_Computer].RemoveButton.Font = 'Microsoft Sans Serif,10'
$_HashFormTabTable[$_Computer].RemoveButton.Add_Click({
$_EnabledItems = #($_HashFormTabTable[$_Computer].EnabledBox.SelectedItems)
$_EnabledItems | Foreach{
$_HashFormTabTable[$_Computer].PotentialBox.Items.Add($_)
$_HashFormTabTable[$_Computer].EnabledBox.Items.Remove($_)
}
})
$_HashFormTabTable[$_Computer].Tab.Controls.Add($_HashFormTabTable[$_Computer].RemoveButton)
####OkButton
$OkButton = New-Object system.Windows.Forms.Button
$OkButton.location = New-Object System.Drawing.Point(440,230)
$OkButton.text = "Ok"
$OkButton.width = 70
$OkButton.height = 30
$OkButton.Font = 'Microsoft Sans Serif,10'
$OkButton.Add_Click({OkClick})
$_HashFormTabTable[$_Computer].Tab.Controls.Add($OkButton)
####CancelButton
$CancelButton = New-Object system.Windows.Forms.Button
$CancelButton.location = New-Object System.Drawing.Point(440,275)
$CancelButton.text = "Cancel"
$CancelButton.width = 70
$CancelButton.height = 30
$CancelButton.Font = 'Microsoft Sans Serif,10'
$CancelButton.Add_Click({CancelClick})
$_HashFormTabTable[$_Computer].Tab.Controls.Add($CancelButton)
}
function OkClick {
Foreach ($_Computer in $_ComputerList) {
$_HashDevices[$_Computer] = New-Object -TypeName PSObject -Property #{
PotentialDevices = #($_HashFormTabTable[$_Computer].PotentialBox.items)
EnabledDevices = #($_HashFormTabTable[$_Computer].EnabledBox.items)
}
}
$Form.Close()
}
function CancelClick {
$Form.Close()
}
Foreach ($_Computer in $_ComputerList){
$_HashComputerTable[$_Computer].PotentialDevices | Foreach {if ($_ -ne $null) {[void] $_HashFormTabTable[$_Computer].PotentialBox.Items.Add($_)}}
$_HashComputerTable[$_Computer].EnabledDevices | Foreach {if ($_ -ne $null) {[void] $_HashFormTabTable[$_Computer].EnabledBox.Items.Add($_)}}
}
[void]$Form.ShowDialog()
I learned a new PowerShell method a couple of days ago - GetNewClosure() - , and so far this is the 3rd question since then that I've answered which uses it :-).
First off, I've simplified your code a bit, because you don't need to store references to all your controls in a global array. I've then also added a call to GetNewClosure() onto your callback scriptblocks.
The (simplified) code is then:
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$Form.Width = 985
$Form.Height = 560
$TabBox = New-object System.Windows.Forms.TabControl
$TabBox.Location = New-Object System.Drawing.size(5,5)
$TabBox.Dock = "Fill"
$Form.Controls.Add($TabBox)
foreach ($item in #("page1", "page2", "page3") )
{
#### tab page
$tabPage = New-Object System.Windows.Forms.TabPage
$tabPage.DataBindings.DefaultDataSourceUpdateMode = 0
$tabPage.Text = $item
$tabBox.Controls.Add($tabPage)
#### disabled listbox
$disabledList = New-Object system.Windows.Forms.ListBox
$disabledList.location = New-Object System.Drawing.Point(10,30)
$disabledList.width = 395
$disabledList.height = 440
$disabledList.SelectionMode = 'MultiExtended'
#( "aaa", "bbb" ) | % { $disabledList.Items.Add($_) }
$tabPage.Controls.Add($disabledList)
#### enabled listbox
$enabledList = New-Object system.Windows.Forms.ListBox
$enabledList.location = New-Object System.Drawing.Point(540,30)
$enabledList.width = 395
$enabledList.height = 440
$enabledList.SelectionMode = 'MultiExtended'
#( "ccc", "ddd" ) | % { $enabledList.Items.Add($_) }
$tabPage.Controls.Add($enabledList)
#### add button
$addButton = New-Object system.Windows.Forms.Button
$addButton.location = New-Object System.Drawing.Point(440,140)
$addButton.text = "-->"
$addButton.width = 70
$addButton.height = 30
$tabPage.Controls.Add($addButton)
$addButton.Add_Click(
{
#( $disabledList.SelectedItems ) | Foreach {
$enabledList.Items.Add($_)
$disabledList.Items.Remove($_)
}
}.GetNewClosure()
)
#### remove button
$removeButton = New-Object system.Windows.Forms.Button
$removeButton.location = New-Object System.Drawing.Point(440,185)
$removeButton.text = "<--"
$removeButton.width = 70
$removeButton.height = 30
$removeButton.Add_Click(
{
#( $enabledList.SelectedItems ) | Foreach {
$disabledList.Items.Add($_)
$enabledList.Items.Remove($_)
}
}.GetNewClosure()
)
$tabPage.Controls.Add($removeButton)
####OkButton
$OkButton = New-Object system.Windows.Forms.Button
$OkButton.location = New-Object System.Drawing.Point(440,230)
$OkButton.text = "Ok"
$OkButton.width = 70
$OkButton.height = 30
$OkButton.Add_Click({OkClick})
$tabPage.Controls.Add($OkButton)
####CancelButton
$CancelButton = New-Object system.Windows.Forms.Button
$CancelButton.location = New-Object System.Drawing.Point(440,275)
$CancelButton.text = "Cancel"
$CancelButton.width = 70
$CancelButton.height = 30
$CancelButton.Font = 'Microsoft Sans Serif,10'
$CancelButton.Add_Click({CancelClick})
$tabPage.Controls.Add($CancelButton)
}
function OkClick {
$Form.Close()
}
function CancelClick {
$Form.Close()
}
[void]$Form.ShowDialog()
In short, your original callbacks were evaluating the expression $_HashFormTabTable[$_Computer].PotentialBox, for example, at the time the callback executed, not when the callback scriptblock was created.
Note that PowerShell retains the last value of an iterator variable when a foreach loop exits - e.g.
PS> foreach ($x in #("aaa", "bbb", "ccc") ) {}
PS> $x
ccc
so when any of your callbacks were executing, they were all getting the last item in the $_HashFormTabTable array because the value of $_Computer was the last value iterated over in the for loop.
Compare the behaviour of this script, for example:
$callbacks = #();
foreach( $item in #( "aaa", "bbb", "ccc" ) )
{
$callbacks += { write-host "callback = '$item'" }
}
write-host "item = '$item'";
foreach( $callback in $callbacks )
{
$callback.Invoke()
}
which outputs
item = 'ccc'
callback = 'ccc'
callback = 'ccc'
callback = 'ccc'
with this one:
$callbacks = #();
foreach( $item in #( "aaa", "bbb", "ccc" ) )
{
$callbacks += { write-host "callback = '$item'" }.GetNewClosure()
}
write-host "item = '$item'"
foreach( $callback in $callbacks )
{
$callback.Invoke()
}
which outputs:
item = 'ccc'
callback = 'aaa'
callback = 'bbb'
callback = 'ccc'
Hope this helps.

How to create check box automatically depends on folder selected using PowerShell?

I need to create a checkbox automatically depends on folder I selected. I create ComboBox, then in the ComboBox, I can select which folder that I want to select. Inside of my folder, I have some file. The file consist of some extension file. I just need to pick 2 extension file from the folder, example(*.txt and *.csv).
After I select the folder, the checkBox will create automatically, the total of the checkBox depends on how many file exist in that folder with specific extension(*.txt and *.csv).
In my code, I already do some stuff, which is select the folder that I need to select, but still struggle with the checkBox. Anyone can help me please. Thank you so much. I really appreciate for the help.
I put my script in the ##2nd Updated.
Updated
Consider to #f6a4 answer, this is the result
The first picture is I just use this path to get the folder
'D:\Data\'
In the first picture, I already double click the folder1 and folder2, but the file do not appear.
The second picture, I specify the folder path
'D:\Data\folder1'
The second picture, the file appear because I specify the folder in the path, so the folder name do not appear in the please select folder box and return this error $CTRL_ListFolder.Items.AddRange( (Get-ChildItem -Path $GH.CurrentFold ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
2n Updated
I updated my script. But the file only appear 1, once I click the folder. And when I change to click other folder, It does not appear the file.
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Global:status = "inactive"
$Global:array = New-Object System.Collections.Generic.List[System.Object]
$Form = New-Object system.Windows.Forms.Form
$Form.text = "BPS Image Automation Utility"
$Form.BackColor = "#f6f6f6"
$Form.AutoSize = $true
$Form.FormBorderStyle = "FixedDialog"
$Form.MaximizeBox = $false
$Form.startposition = "centerscreen"
$Form.WindowState = 'Maximized'
$Label1 = New-Object system.Windows.Forms.Label
$Label1.text = "Please select the image"
$Label1.AutoSize = $true
$Label1.width = 25
$Label1.height = 10
$Label1.location = New-Object System.Drawing.Point(50,50)
$Label1.Font = 'Microsoft Sans Serif,10'
$Label1.ForeColor = "#000000"
$label1.AutoSize = $true
$Button3 = New-Object system.Windows.Forms.Button
$Button3.BackColor = "#136aa4"
$Button3.ForeColor = "#ffffff"
$Button3.text = "Done"
$Button3.width = 90
$Button3.height = 32
$Button3.AutoSize = $true
$Button3.UseCompatibleTextRendering = $True
$Button3.UseVisualStyleBackColor = $False
# $Button3.location = New-Object System.Drawing.Point(1700,920)
$Button3.Font = 'Microsoft Sans Serif,10'
# $Button3.Visible = $false
$Button2 = New-Object system.Windows.Forms.Button
$Button2.BackColor = "#136aa4"
$Button2.ForeColor = "#ffffff"
$Button2.text = "Delete"
$Button2.width = 90
$Button2.height = 32
$Button2.UseCompatibleTextRendering = $True
$Button2.UseVisualStyleBackColor = $False
$Button2.AutoSize = $true
# $Button2.location = New-Object System.Drawing.Point(1600,920)
$Button2.Font = 'Microsoft Sans Serif,10'
# $Button2.Visible = $false
$Panel = New-Object System.Windows.Forms.TableLayoutPanel
$panel.Dock = "Fill"
$panel.ColumnCount = 1
$panel.RowCount = 1
$panel.CellBorderStyle = "single"
$panel.ColumnStyles.Add((new-object System.Windows.Forms.ColumnStyle([System.Windows.Forms.SizeType]::Percent, 100)))
$panel.RowStyles.Add((new-object System.Windows.Forms.RowStyle([System.Windows.Forms.SizeType]::Percent, 100)))
$Groupbox1 = New-Object system.Windows.Forms.Groupbox
$Groupbox1.text = "Job Handling"
$Groupbox1.Font = 'Microsoft Sans Serif,9'
$Groupbox1.AutoSize = $true
$Groupbox1.ForeColor = "#032d5d"
$Groupbox1.location = New-Object System.Drawing.Point(8,13)
$Groupbox1.Padding = New-Object -TypeName System.Windows.Forms.Padding -ArgumentList (0,5,5,0)
$Groupbox1.Dock = "fill"
$Groupbox1.UseCompatibleTextRendering = $True
$Groupbox2 = New-Object system.Windows.Forms.Groupbox
$Groupbox2.text = "Job Information"
$Groupbox2.Font = 'Microsoft Sans Serif,9'
$Groupbox2.AutoSize = $true
$Groupbox2.ForeColor = "#032d5d"
$Groupbox2.Dock = "None"
$Groupbox2.UseCompatibleTextRendering = $True
$ComboBox1 = New-Object system.Windows.Forms.ComboBox
$ComboBox1.BackColor = "#e8f3ff"
$ComboBox1.width = 190
$ComboBox1.height = 20
$ComboBox1.location = New-Object System.Drawing.Point(35,80)
$ComboBox1.Font = 'Microsoft Sans Serif,12'
$ComboBox1.AutoSize = $true
$ImageList = #(Get-ChildItem -Directory "D:\Process")
foreach ($img in $ImageList) {
$ComboBox1.Items.Add($img)
}
$ComboBox1.Add_Click({
if($ComboBox1.SelectedItem){
$Checkbox.Visible = $true
}
})
$Checkboxes += New-Object System.Windows.Forms.CheckBox
$Checkboxes = #()
$y = 20
$files = Get-ChildItem "D:\Process\$img" -Filter *.txt, *.csv
$files
foreach ($file in $files)
{
$Checkbox = New-Object System.Windows.Forms.CheckBox
$Checkbox.Text = $file
$Checkbox.Location = New-Object System.Drawing.Size(10,$y)
$Checkbox.Size = New-Object System.Drawing.Size(330,20)
$y += 30
$Groupbox2.Controls.Add($Checkbox)
$Checkboxes += $Checkbox
$Checkbox.Visible = $false
}
$Form.controls.AddRange(#($Panel))
$Panel.controls.AddRange(#($Groupbox1))
$Groupbox1.Controls.AddRange(#($Groupbox2, $ComboBox1, $Label1, $Button3, $Button2))
[void]$Form.Show()
$g2w = $Form.Width - 90
$g2h = $Form.Height - 270
$g2h
$Groupbox2.location = New-Object System.Drawing.Point(35,110)
$Groupbox2.size = New-Object System.Drawing.Size($g2w,$g2h)
$Groupbox2.AutoSize = $true
$bt2_w = $g2w - 55
$bt2_h = $g2h + 130
$Button2.location = New-Object System.Drawing.Point($bt2_w,$bt2_h)
$bt3_w = $g2w - 160
$Button3.location = New-Object System.Drawing.Point($bt3_w,$bt2_h)
$Form.Visible = $false
[void]$Form.ShowDialog()
This should do exactly what you want. By double click on a Directory you can browse through subdirectories as well.
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
# Global variables
$GH = [hashtable]::Synchronized(#{})
$GH.FolderPath = 'C:\Users\myUser\Desktop\csvfiles'
$GH.CurrentFolderPath = $GH.FolderPath
$GH.FileMask = #('*.txt','*.csv')
# windows form
$form = New-Object System.Windows.Forms.Form
$form.Visible = $false
[void]$form.SuspendLayout()
$form.Text = "File Selection"
$form.ClientSize = New-Object System.Drawing.Size(320,430)
$form.StartPosition = 'CenterScreen'
$form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
# tab control
$CTRL_TabCtrl = New-Object System.Windows.Forms.TabControl
$CTRL_TabCtrl.Location = New-Object System.Drawing.Point(5,5)
$CTRL_TabCtrl.Size = New-Object System.Drawing.Size(310,420)
[void]$form.Controls.Add($CTRL_TabCtrl)
$CTRL_Tab1 = New-Object System.Windows.Forms.TabPage
$CTRL_Tab1.AutoSize = $true
$CTRL_Tab1.Text = 'Main'
$CTRL_Tab1.TabIndex = 1
[void]$CTRL_TabCtrl.Controls.Add($CTRL_Tab1)
# list folder
$CTRL_label10 = New-Object System.Windows.Forms.Label
$CTRL_label10.Location = New-Object System.Drawing.Point(10,10)
$CTRL_label10.Size = New-Object System.Drawing.Size(260,20)
$CTRL_label10.Name = 'Label10'
$CTRL_label10.Text = 'Please select a folder:'
[void]$CTRL_Tab1.Controls.Add($CTRL_label10)
$CTRL_ListFolder = New-Object System.Windows.Forms.Listbox
$CTRL_ListFolder.Location = New-Object System.Drawing.Point(10,30)
$CTRL_ListFolder.Size = New-Object System.Drawing.Size(280,60)
$CTRL_ListFolder.SelectionMode = [System.Windows.Forms.SelectionMode]::One
$CTRL_ListFolder.Items.AddRange( (Get-ChildItem -Path $GH.CurrentFolderPath -Directory).Name )
$CTRL_ListFolder.Enabled = $true
$CTRL_ListFolder.Add_MouseDoubleClick( {
$listFolder_innerevent = $true
if( $CTRL_ListFolder.SelectedItem -eq '..' ) {
$GH.CurrentFolderPath = $GH.CurrentFolderPath.Substring( 0, $GH.CurrentFolderPath.LastIndexOf( '\' ) )
[void]$CTRL_ListFolder.Items.Clear()
if( $GH.CurrentFolderPath.Length -gt $GH.FolderPath.Length ) {
[void]$CTRL_ListFolder.Items.Add( '..' )
}
$CTRL_ListFolder.Items.AddRange( (Get-ChildItem -Path $GH.CurrentFolderPath -Directory).Name )
[void]$CTRL_CheckListBox.Items.Clear()
$files = (Get-ChildItem -Path ($GH.CurrentFolderPath + '\*') -Include $GH.FileMask -File ).Name
if( $files ) {
[void]$CTRL_CheckListBox.Items.AddRange( $files )
}
}
else {
if( (Get-ChildItem -Path ($GH.CurrentFolderPath + '\' + $CTRL_ListFolder.SelectedItem) -Directory).Name ) {
$GH.CurrentFolderPath += '\' + $CTRL_ListFolder.SelectedItem
[void]$CTRL_ListFolder.Items.Clear()
[void]$CTRL_ListFolder.Items.Add( '..' )
[void]$CTRL_ListFolder.Items.AddRange( (Get-ChildItem -Path $GH.CurrentFolderPath -Directory).Name )
[void]$CTRL_CheckListBox.Items.Clear()
$files = (Get-ChildItem -Path ($GH.CurrentFolderPath + '\*') -Include $GH.FileMask -File ).Name
if( $files ) {
[void]$CTRL_CheckListBox.Items.AddRange( $files )
}
}
}
} )
[void]$CTRL_Tab1.Controls.Add($CTRL_ListFolder)
# list folder with check boxes for files
$CTRL_label12 = New-Object System.Windows.Forms.Label
$CTRL_label12.Location = New-Object System.Drawing.Point(10,100)
$CTRL_label12.Size = New-Object System.Drawing.Size(260,20)
$CTRL_label12.Name = 'Label12'
$CTRL_label12.Text = 'Files found:'
[void]$CTRL_Tab1.Controls.Add($CTRL_label12)
$CTRL_CheckListBox = New-Object System.Windows.Forms.CheckedListbox
$CTRL_CheckListBox.Location = New-Object System.Drawing.Point(10,120)
$CTRL_CheckListBox.Size = New-Object System.Drawing.Size(280,230)
$CTRL_CheckListBox.CheckOnClick = $true
$CTRL_CheckListBox.Enabled = $true
$files = (Get-ChildItem -Path ($GH.CurrentFolderPath + '\*') -Include $GH.FileMask -File ).Name
if( $files ) {
[void]$CTRL_CheckListBox.Items.AddRange( $files )
}
[void]$CTRL_Tab1.Controls.Add($CTRL_CheckListBox)
$CTRL_OKButton1 = New-Object System.Windows.Forms.Button
$CTRL_OKButton1.Location = New-Object System.Drawing.Point(70,365)
$CTRL_OKButton1.Size = New-Object System.Drawing.Size(75,23)
$CTRL_OKButton1.Text = 'OK'
$CTRL_OKButton1.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $CTRL_OKButton1
[void]$CTRL_Tab1.Controls.Add($CTRL_OKButton1)
$CTRL_CancelButton1 = New-Object System.Windows.Forms.Button
$CTRL_CancelButton1.Location = New-Object System.Drawing.Point(150,365)
$CTRL_CancelButton1.Size = New-Object System.Drawing.Size(75,23)
$CTRL_CancelButton1.Text = 'Cancel'
$CTRL_CancelButton1.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CTRL_CancelButton1
[void]$CTRL_Tab1.Controls.Add($CTRL_CancelButton1)
[void]$form.ResumeLayout()
$userInput = $form.ShowDialog()
if ($userInput -eq [System.Windows.Forms.DialogResult]::OK) {
# User clicked OK Button
}

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")
}

Powershell Forms refresh GUI

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.