How to create check box automatically depends on folder selected using PowerShell? - 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
}

Related

Can't populate DataGridView column with calendar meeting property

I'm working on a little side project of listing outlook calendar meetings in the form data grid view.
I can populate columns with Subject and Start Date with no problem. For some reason, I can not populate a column with .DayOfWeekMask value, even though I can access this property via CLI. Any thoughts? Code below
add-type -AssemblyName 'System.Windows.Forms'
Add-Type -AssemblyName 'System.Drawing'
Add-Type -AssemblyName 'PresentationFramework'
$4 =
"BASE64 code"
$today = get-date
$Script:selection = #()
add-type -AssemblyName "Microsoft.Office.Interop.Outlook"
$outlookFolders = "Microsoft.Office.Interop.Outlook.OlDefaultFolders" -as [type]
$outlook = New-Object -ComObject outlook.application
$namespace = $outlook.GetNamespace("MAPI")
$folder = $namespace.GetDefaultFolder($outlookFolders::olFolderCalendar)
$items = $folder.Items
$meetings = $items|?{$_.isRecurring -eq $true -and $_.Subject -notlike "*Canceled*" <#-and $_.GetRecurrencePattern().DayOfWeekMask -eq 18#>}|Select Subject, Start, #{l='Mask';e={$_.GetRecurrencePattern().DayOfWeekMask}}
$bitmap3 = New-Object System.Windows.Media.Imaging.BitmapImage
$bitmap3.BeginInit()
$bitmap3.StreamSource = [System.IO.MemoryStream][System.Convert]::FromBase64String($4)
$bitmap3.EndInit()
$bitmap3.Freeze()
$image3 = [System.Drawing.Bitmap][System.Drawing.Image]::FromStream($bitmap3.StreamSource)
$icon3 = [System.Drawing.Icon]::FromHandle($image3.GetHicon())
$main2 = New-Object System.Windows.Forms.Form
$main2.Icon = $icon3
$main2.ClientSize = '600,600'
$main2.MinimizeBox = $false
$main2.MaximizeBox = $false
$main2.Text = 'Options'
$main2.AutoSize = $true
$grid = New-Object System.Windows.Forms.DataGridView
$grid.Location = '5,5'
$grid.Height = 500
$grid.Width = 390
$grid.ColumnHeadersVisible = $true
$grid.AutoSizeColumnsMode = 'AllCells'
$grid.ColumnCount = 3
$grid.columns[0].Name = 'Name'
$grid.Columns[1].Name = 'Time'
$grid.Columns[2].Name = 'Day Mask'
$grid.MultiSelect = $true
$grid.SelectionMode = 'FullRowSelect'
$meetings|%{$grid.Rows.Add($($_.Subject), $($_.Start)), $($_.Mask)}
$button = [System.Windows.Forms.Button]::new()
$button.Location = [System.Drawing.Point]::new(5,540)
$button.Size = [System.Drawing.Size]::new(100,50)
$button.Text = 'OK'
$button.Add_Click({
$grid.SelectedRows|%{
$Script:selection += [pscustomobject]#{
Name = $grid.Rows[$_.Index].Cells[0].Value
Time = $grid.Rows[$_.Index].Cells[1].Value
}
}
})
$main2.Controls.AddRange(#($grid,$button))
$main2.ShowDialog()
update you datagrid wiht this one
$grid = New-Object System.Windows.Forms.DataGridView
$grid.Location = '5,5'
$grid.Height = 500
$grid.Width = 390
$grid.ColumnHeadersVisible = $true
$grid.AutoSizeColumnsMode = 'AllCells'
$grid.MultiSelect = $true
$grid.SelectionMode = 'FullRowSelect'
$array.AddRange($meetings)
$grid.DataSource=($array)
======= this datasourge work eveytime..
Based on the answer of #Kemal I removed .ColumnCount and subsequent Name properties. Created new ArrayList via $array = [System.Collections.ArrayList]::new() abd then applied Kemal's solution.
In th end the script looks like this.
add-type -AssemblyName 'System.Windows.Forms'
Add-Type -AssemblyName 'System.Drawing'
Add-Type -AssemblyName 'PresentationFramework'
$4 =
"BASE64 CODE"
$today = get-date
$selection =#()
$array = [System.Collections.ArrayList]::new()
add-type -AssemblyName "Microsoft.Office.Interop.Outlook"
$outlookFolders = "Microsoft.Office.Interop.Outlook.OlDefaultFolders" -as [type]
$outlook = New-Object -ComObject outlook.application
$namespace = $outlook.GetNamespace("MAPI")
$folder = $namespace.GetDefaultFolder($outlookFolders::olFolderCalendar)
$items = $folder.Items
$meetings = $items|?{$_.isRecurring -eq $true -and $_.Subject -notlike "*Canceled*" |Select Subject, Start, #{l='Mask';e={$_.GetRecurrencePattern().DayOfWeekMask}}
$bitmap3 = New-Object System.Windows.Media.Imaging.BitmapImage
$bitmap3.BeginInit()
$bitmap3.StreamSource = [System.IO.MemoryStream][System.Convert]::FromBase64String($4)
$bitmap3.EndInit()
$bitmap3.Freeze()
$image3 = [System.Drawing.Bitmap][System.Drawing.Image]::FromStream($bitmap3.StreamSource)
$icon3 = [System.Drawing.Icon]::FromHandle($image3.GetHicon())
$main2 = New-Object System.Windows.Forms.Form
$main2.Icon = $icon3
$main2.ClientSize = '600,600'
$main2.MinimizeBox = $false
$main2.MaximizeBox = $false
$main2.Text = 'Options'
$main2.AutoSize = $true
$grid = New-Object System.Windows.Forms.DataGridView
$grid.Location = '5,5'
$grid.Height = 500
$grid.Width = 390
$grid.ColumnHeadersVisible = $true
$grid.AutoSizeColumnsMode = 'AllCells'
$grid.MultiSelect = $true
$grid.SelectionMode = 'FullRowSelect'
$array.AddRange($meetings)
$grid.DataSource=($array)
$button = [System.Windows.Forms.Button]::new()
$button.Location = [System.Drawing.Point]::new(5,540)
$button.Size = [System.Drawing.Size]::new(100,50)
$button.Text = 'OK'
$button.Add_Click({
$grid.SelectedRows|%{
$Script:selection += [pscustomobject]#{
Name = $grid.Rows[$_.Index].Cells[0].Value
Time = $grid.Rows[$_.Index].Cells[1].Value
DayofWeek = $grid.Rows[$_.Index].Cells[2].Value
}
}
})
$main2.Controls.AddRange(#($grid,$button))
$main2.ShowDialog()

I want to monitor the date and time of a file every 30 seconds

I want to monitor the date and time of a file. I wrote the code that do the job as I want but I can't reposition the gui window. I tried all I could find like "start-job" or create a new runspace but I don't get any results in richtextbox. Any suggestion is welcome.
$targetFile = "full path"
# Function - Add Text to RichTextBox
function Add-RichTextBox{
[CmdletBinding()]
param ($text)
#$richtextbox_output.Text += "`tCOMPUTERNAME: $ComputerName`n"
$richtext.Text += "$text"
$richtext.Text += "`n"
}
# Windows Form
$form = New-Object System.Windows.Forms.Form
$form.Text = "Monitor script"
$form.Size = New-Object System.Drawing.Size(400,300)
$form.StartPosition = 'CenterScreen'
$Font = New-Object System.Drawing.Font("Tahoma",11)
$Form.Font = $Font
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(20,40)
$label.Size = New-Object System.Drawing.Size(200,20)
$label.Text = (Get-Date).ToString()
$form.Controls.Add($label)
$StartButton = New-Object System.Windows.Forms.Button
$StartButton.Location = New-Object System.Drawing.Point(150,220)
$StartButton.Size = New-Object System.Drawing.Size(100,33)
$StartButton.Text = 'Start'
#$StartButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $StartButton
$form.Controls.Add($StartButton)
$StartButton.Add_click({
while($true){
$lastdate = Get-ChildItem $targetFile
$Date = $lastdate.LastAccessTime.ToString()
Add-RichTextBox "$date"
$richtext.SelectionStart = $richtext.TextLength
$richText.ScrollToCaret()
#$richtext.refresh()
#$form.refresh()
Start-sleep 30
}
})
## the Rich text box
$richtext = new-object System.Windows.Forms.RichTextBox
$richtext.Location = New-Object System.Drawing.Point(20,60)
$richtext.multiline = $true
$richtext.Name = "Results"
$richtext.text = "Results:`n"
$richtext.scrollbars = "Both"
$richtext.Height = 120
$richtext.width = 350
$richtext.font = new-object system.drawing.font "Lucida Console",10
$Form.controls.add($richtext)
$Form.Add_Shown({$Form.Activate()})
$form.ShowDialog()
Continuing from my comment to use a Timer on your form (if you absolutely do not want a FileSystemWatcher), here's how you can do that:
$targetFile = "D:\Test\blah.txt"
$lastAccessed = (Get-Date) # a variable to keep track of the last LastAccessTime of the file
# Windows Form
$form = New-Object System.Windows.Forms.Form
$form.Text = "Monitor script"
$form.Size = New-Object System.Drawing.Size(400,300)
$form.StartPosition = 'CenterScreen'
$Font = New-Object System.Drawing.Font("Tahoma",11)
$form.Font = $Font
# Label
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(20,40)
$label.Size = New-Object System.Drawing.Size(200,20)
$label.Text = (Get-Date).ToString()
$form.Controls.Add($label)
# Button
$StartButton = New-Object System.Windows.Forms.Button
$StartButton.Location = New-Object System.Drawing.Point(150,200)
$StartButton.Size = New-Object System.Drawing.Size(100,33)
$StartButton.Text = 'Start'
$form.Controls.Add($StartButton)
$StartButton.Add_click({
$timer.Enabled = $true
$timer.Start()
})
# RichTextBox
$richtext = New-Object System.Windows.Forms.RichTextBox
$richtext.Location = New-Object System.Drawing.Point(20,60)
$richtext.Multiline = $true
$richtext.Name = "Results"
$richtext.Text = "Results:`r`n"
$richtext.ScrollBars = "Both"
$richtext.Height = 120
$richtext.Width = 350
$richtext.Font = New-Object System.Drawing.Font "Lucida Console",10
$form.Controls.Add($richtext)
# Timer
$timer = New-Object System.Windows.Forms.Timer
$timer.Interval = 30000 # 30 seconds
$timer.Enabled = $false # disabled at first
$timer.Add_Tick({
$file = Get-Item -Path $targetFile -ErrorAction SilentlyContinue
# if we can find the file and its last AccessedTime is not
# the same as we already stored in variable $lastAccessed
# use script-scoping here, so $script:lastAccessed instead of $lastAccessed
if ($file -and $file.LastAccessTime -gt $script:lastAccessed) {
$richtext.AppendText("$($file.LastAccessTime.ToString())`r`n")
$script:lastAccessed = $file.LastAccessTime # remember this new datetime
}
})
$form.ShowDialog()
# Important: Clean up
$timer.Stop()
$timer.Dispose()
$richtext.Dispose()
$form.Dispose()

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);

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