PowerShell checkbox controls button function - forms

This is my very first school project in PowerShell. Its going to be simple. Type path and press button to Get-Acl, which works, but I want to have an option for recurse. Which also works, but I have not been able to make a checkbox determine what function button has.. Specifically The checkboxstatechanged is what I need help with.
function ChckBx_chkd {
$table = Get-ChildItem -directory -path $Textbox1.Text -recurse
$Rtbx = #()
foreach ($dir in $table)
{
$Access = (Get-Acl $dir.FullName).Access
$Rtbx += $dir.PSPath
$Rtbx += $Access | Format-Table | out-string
}
}
function ChkcBx_unchkd {
$Rtbx.Text = (Get-Acl $Textbox1.Text).Access| Format-Table| Out-String
}
$Form = New-Object System.Windows.Forms.Form
#Själva Formen
$Form.Text = "ACL GUI"
$Font = New-Object System.Drawing.Font("Lucida Console",8)
$Form.Font = $Font
$Form.Width = 1000
$Form.Height = 500
$Rtbx = New-Object System.Windows.Forms.RichTextBox
$Rtbx.Location = '200, 100'
$Rtbx.Width = 750
$Rtbx.Font = $Font
$Rtbx.Height = 300
$Rtbx.Font
$Form.Controls.Add($Rtbx)
$Chkbx1 = New-Object System.Windows.Forms.CheckBox
$Chkbx1.Location = '50, 150'
$Chkbx1.Text = "undermappar"
$Chkbx1.Checked = $true
$Chkbx1.Add_CheckStateChanged({
if($Chkbx1.checked) {
$Btn1Click = ChckBx_chkd
}
else
{
$Btn1Click = ChkcBx_unchkd
}
})
$Form.Controls.Add($Chkbx1)
$Textbox1 = New-Object System.Windows.Forms.TextBox
$Textbox1.Location = '50, 50'
$Textbox1.Width = 700
$Form.Controls.Add($Textbox1)
$Btn1 = New-Object System.Windows.Forms.Button
$Btn1.Location = '50, 100'
$Btn1.Text = "Get ACL"
$Btn1.Font =
$Btn1.Width = 100
$Btn1.Add_Click($Btn1Click)
$Form.Controls.Add($Btn1)
$Form.ShowDialog()

I have to say that with the code formatted as it is, it makes it very hard to see where the functions and loops start and end. Pick a style a stick with it.
Your function names are spelt oddly which is confusing ChckBx_unchkd and ChkcBx_chkd - why reverse ck in the prefix?
Your ChkcBx_chkd code doesn't appear to work - you're redefining the variable $Rtbx as an array where you want to set the .Text property.
You have no default value set so $Btn1Click is undefined until you change the checkbox state at least once.
Your assignment of $Btn1Click = ChckBx_chkd actually calls that function at that point where you appear be using it as a reference which you then call later. You should do $Btn1Click = "ChckBx_chkd" (i.e. a string name of the function) then later use Invoke-Expression $Btn1Click
The scope of your variables is not the same. Changing $Btn1Click does not affect the value. Write-Host is your friend - print the variables out to help you debug what values they have. I've used Get-Variable/Set-Variable so I can use the variables in the global scope.
Revised code
function ChckBx_chkd {
Write-Host "ChckBx_chkd called"
$table = Get-ChildItem -directory -path $Textbox1.Text -recurse
$Rtbx.Text = ""
foreach ($dir in $table) {
$Access = (Get-Acl $dir.FullName).Access
$Rtbx.Text += $dir.PSPath
$Rtbx.Text += $Access | Format-Table | out-string
}
}
function ChkcBx_unchkd {
Write-Host "ChkcBx_unchkd called"
$Rtbx.Text = (Get-Acl $Textbox1.Text).Access | Format-Table| Out-String
}
Set-Variable -Name Btn1Click -Value "ChckBx_chkd" -Scope Global
$Font = New-Object System.Drawing.Font("Lucida Console",8)
$Form = New-Object System.Windows.Forms.Form
$Form.Text = "ACL GUI"
$Form.Font = $Font
$Form.Width = 1000
$Form.Height = 500
$Rtbx = New-Object System.Windows.Forms.RichTextBox
$Rtbx.Location = '200, 100'
$Rtbx.Width = 750
$Rtbx.Font = $Font
$Rtbx.Height = 300
$Rtbx.Font
$Form.Controls.Add($Rtbx)
$Chkbx1 = New-Object System.Windows.Forms.CheckBox
$Chkbx1.Location = '50, 150'
$Chkbx1.Text = "undermappar"
$Chkbx1.Checked = $true
$Chkbx1.Add_CheckStateChanged({
Write-Host $Chkbx1.checked $(Get-Variable -Name Btn1Click -Scope Global).Value
if ($Chkbx1.checked) {
Set-Variable -Name Btn1Click -Value "ChckBx_chkd" -Scope Global
} else {
Set-Variable -Name Btn1Click -Value "ChkcBx_unchkd" -Scope Global
}
Write-Host $Chkbx1.checked $(Get-Variable -Name Btn1Click -Scope Global).Value
})
$Form.Controls.Add($Chkbx1)
$Textbox1 = New-Object System.Windows.Forms.TextBox
$Textbox1.Location = '50, 50'
$Textbox1.Width = 700
$Form.Controls.Add($Textbox1)
$Btn1 = New-Object System.Windows.Forms.Button
$Btn1.Location = '50, 100'
$Btn1.Text = "Get ACL"
$Btn1.Font =
$Btn1.Width = 100
$Btn1.Add_Click({Invoke-Expression $(Get-Variable -Name Btn1Click -Scope Global).Value})
$Form.Controls.Add($Btn1)
$Form.ShowDialog()

Related

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

Update DataGridView via button click

I am currently trying to update my datagridview via button click, add a user via text box and clicking a button i want the datagridview to update to reflect the current stat of the database.
I have the datagridview showing up on launch of the software, but when I click the add button and try to refresh it, the database does not show.
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Data
Add-Type -AssemblyName System.Collections
$jsonDB = Get-Content 'C:\Support\HardwareCollection.json' | Out-String | ConvertFrom-Json
#JsonDb has $JsonDB.update and $JsonDB.Date
$tableData = New-Object System.Collections.ArrayList
$tableData.AddRange($jsonDB)
$Form = New-Object System.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(1050, 425)
$Form.MaximizeBox = $False
$Form.StartPosition = "CenterScreen"
$Form.FormBorderStyle = 'Fixed3D'
$Form.Text = "Hardware Collection"
$AddClientNButton = new-object System.Windows.Forms.Button
$AddClientNButton.Location = new-object system.drawing.size(61,90)
$AddClientNButton.Size = new-object system.drawing.size(80,50)
$AddClientNButton.Text = "Add Client"
$AddClientNButton.Add_Click({AddClient})
$AddClientNButton.TabIndex = 10
$Form.Controls.Add($AddClientNButton)
$UserNametextBox = New-Object System.Windows.Forms.TextBox
$UserNametextBox.Location = New-Object System.Drawing.Point(1,1)
$UserNametextBox.Size = New-Object System.Drawing.Size(300,20)
$UserNametextBox.text="User Name"
$UserNametextBox.MaxLength = 6
$UserNametextBox.Add_Click({$this.SelectAll(); $this.Focus()})
$UserNametextBox.TabIndex = 0
$form.Controls.Add($UserNametextBox)
$dataGridView = New-Object System.Windows.Forms.DataGridView -Property #{
Size = New-Object System.Drawing.Size(500, 200)
Location = New-Object System.Drawing.Size(1, 150)
ColumnHeadersVisible = $True
DataSource = $tableData
AutoSizeColumnsMode = 'AllCells'
ColumnHeadersHeightSizeMode = 'AutoSize'
}
function AddClient
{
$jsonDB = Get-Content 'C:\Support\HardwareCollection.json' | Out-String | ConvertFrom-Json
$json.username
$Date = Get-Date -Format "MM/dd/yyyy HH:mm:ss K"
$Username = $UserNametextBox.text
if($jsonDB.username -eq $null)
{
$NewEntryItems=$Usernames
}
else
{
if($jsonDB.username -contains $Username)
{
$NewEntryItems =$null
}
else
{
$NewEntryItems = $username
}
}
$CollectionData = ForEach ($Username in $NewEntryItems)
{
New-Object PSObject -Property #{
Username = $Username
Date = $Date
}
}
$jsonDB += $CollectionData
$jsonDB | ConvertTo-Json -Compress |
Set-Content C:\Support\HardwareCollection.json
#refresh datagridview
$dataGridView.DataBindings.DefaultDataSourceUpdateMode = 0
$jsonDB = Get-Content 'C:\Support\HardwareCollection.json' | Out-String | ConvertFrom-Json
#$dataGridView.DataSource = $jsonDB
$tableData = New-Object System.Collections.ArrayList
$tableData.AddRange($jsonDB)
$dataGridView = New-Object System.Windows.Forms.DataGridView -Property #{
Size = New-Object System.Drawing.Size(500, 200)
Location = New-Object System.Drawing.Size(1, 150)
ColumnHeadersVisible = $True
DataSource = $tableData
AutoSizeColumnsMode = 'AllCells'
ColumnHeadersHeightSizeMode = 'AutoSize'
}
}
$Form.Controls.Add($dataGridView)
$Form.ShowDialog()
Any help would be amazing!!
I found the answer on another page. dumping this in fixed my issue.
$script:datagridview.DataBindings.DefaultDataSourceUpdateMode = 0
$script:datagridview.DataSource= $script:TableData
$script:datagridview.Refresh
Referenced Page

Populate ComboBox2 depending on ComboBox1 selection

Few days of searching and trying multiple options, but nothing is working actually. With the previous code posted.
I've imported all my objects from XAML (all set in variables), I don't know if that would be a problem for that. I don't think since everything else seems to work properly.
I just want my Tab2CBB2 to show values depending on the selection of Tab1CBB1. Anyone could help ? (I haven't paste the entire code, neither the paths but you can probably help me with that). Note that those are two of my multiple tries. Thanks
[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
[xml]$xaml = #" ...
"#
#Read XAML (Parse it)
$reader=(New-Object System.Xml.XmlNodeReader $XAML)
$Window=[Windows.Markup.XamlReader]::Load( $reader )
$listQA14 = Get-ChildItem $pathQA14 -name
$listQA15 = Get-ChildItem $pathQA15 -name
$listDBQA = Get-ChildItem $pathDBQA -name
$Tab1CBB1_SelectedIndexChanged= {
$Tab1CBB2.Items.Clear() # Clear the list
$Tab1CBB2.Text = $null # Clear the current entry
Switch ($Tab1CBB1.Text) {
'QA14' {
$ListQA14 | ForEach { $Tab1CBB2.Items.Add($_) }
}
'QA15' {
$ListQA15 | ForEach { $Tab1CBB2.Items.Add($_) }
}
'ARIELDBQA' {
$ListDBQA | ForEach { $Tab1CBB2.Items.Add($_) }
}
}
}
$Tab1CBB1.add_SelectedIndexChanged($Tab1CBB1_SelectedIndexChanged)
#Displays the Window
$Window.ShowDialog() | out-null
Here is another option tried :
#ComboBox1------
$ItemsCBB1 = #('ARIELDBQA','QA14','QA15')
foreach ($Item in $ItemsCBB1) {
$Tab1CBB1.Items.Add($Item)
}
#ComboBox2-------
if ($Tab1CBB1.SelectedItem -eq 'QA14') {
$Tab1CBB2.Items.Clear()
foreach ($Serie in $listQA14) {
$Tab1CBB2.Items.Add($Serie)
}
}
elseif ($Tab1CBB1.SelectedItem -eq 'QA15') {
$Tab1CBB2.Items.Clear()
foreach ($Serie in $listQA15) {
$Tab1CBB2.Items.Add($Serie)
}
}
elseif ($Tab1CBB1.SelectedItem -eq 'listDBQA') {
$Tab1CBB2.Items.Clear()
foreach ($Serie in $listDBQA) {
$Tab1CBB2.Items.Add($Serie)
}
}
Tried this also : $Selection = $Tab1CBB1.SelectedItem.ToString()
Variable $selection put after 'if', but not working
Note that when I indicate what the current selection would be, it is working properly. The problem seems to come from 'recording' the selection a the time of clicking... Thnaks !
Basically, all you have to do is inside the $Tab1CBB1_SelectedIndexChanged scriptblock use the various lists with script scoping.
Without that, the variables are unknown inside the script block.
$Tab1CBB1_SelectedIndexChanged = {
$Tab1CBB2.Items.Clear() # Clear the list
$Tab1CBB2.Text = $null # Clear the current entry
switch ($Tab1CBB1.Text) {
'QA14' { $script:ListQA14 | ForEach-Object { $Tab1CBB2.Items.Add($_) } }
'QA15' { $script:ListQA15 | ForEach-Object { $Tab1CBB2.Items.Add($_) } }
'ARIELDBQA' { $script:ListDBQA | ForEach-Object { $Tab1CBB2.Items.Add($_) } }
}
}
Another method could be to dynamically get the items to enter in the combobox, especially since these are file lists and can change while your form is being used:
$Tab1CBB1_SelectedIndexChanged = {
$Tab1CBB2.Items.Clear() # Clear the list
$Tab1CBB2.Text = $null # Clear the current entry
switch ($Tab1CBB1.Text) {
'QA14' { $path = $script:pathQA14 ; break }
'QA15' { $path = $script:pathQA15 ; break }
'ARIELDBQA' { $path = $script:pathDBQA }
}
Get-ChildItem -Path $path -Name | ForEach-Object { $Tab1CBB2.Items.Add($_) }
}
A simple example of what you seem to be after is something like this.
### Powershell populate ComboBox 2 based on ComboBox 1 Selection
Add-type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$labelDoubleClickOnAnyItem = New-Object 'System.Windows.Forms.Label'
$listbox2 = New-Object 'System.Windows.Forms.ListBox'
$listbox1 = New-Object 'System.Windows.Forms.ListBox'
$buttonOK = New-Object 'System.Windows.Forms.Button'
$form1_Load={
$items=1..9 |
ForEach-Object {"List item $_"}
$listbox1.Items.AddRange($items)
}
$listbox1_MouseDoubleClick=[System.Windows.Forms.MouseEventHandler]{
$listbox2.Items.Add($listbox1.SelectedItem)
$listbox1.Items.Remove($listbox1.SelectedItem)
}
$listbox2_MouseDoubleClick=[System.Windows.Forms.MouseEventHandler]{
$listbox1.Items.Add($listbox2.SelectedItem)
$listbox2.Items.Remove($listbox2.SelectedItem)
}
$form1.Controls.Add($labelDoubleClickOnAnyItem)
$form1.Controls.Add($listbox2)
$form1.Controls.Add($listbox1)
$form1.Controls.Add($buttonOK)
$form1.AcceptButton = $buttonOK
$form1.ClientSize = '378, 388'
$form1.FormBorderStyle = 'FixedDialog'
$form1.MaximizeBox = $False
$form1.MinimizeBox = $False
$form1.Name = 'form1'
$form1.StartPosition = 'CenterScreen'
$form1.Text = 'Form'
$form1.add_Load($form1_Load)
$labelDoubleClickOnAnyItem.Font = 'Microsoft Sans Serif, 9.75pt, style=Bold, Italic'
$labelDoubleClickOnAnyItem.Location = '13, 13'
$labelDoubleClickOnAnyItem.Name = 'labelDoubleClickOnAnyItem'
$labelDoubleClickOnAnyItem.Size = '353, 41'
$labelDoubleClickOnAnyItem.TabIndex = 3
$labelDoubleClickOnAnyItem.Text = 'Double click on any item to move it from one box to the other.'
$listbox2.FormattingEnabled = $True
$listbox2.Location = '200, 67'
$listbox2.Name = 'listbox2'
$listbox2.Size = '166, 277'
$listbox2.Sorted = $True
$listbox2.TabIndex = 2
$listbox2.add_MouseDoubleClick($listbox2_MouseDoubleClick)
$listbox1.FormattingEnabled = $True
$listbox1.Location = '12, 67'
$listbox1.Name = 'listbox1'
$listbox1.Size = '167, 277'
$listbox1.Sorted = $True
$listbox1.TabIndex = 1
$listbox1.add_MouseDoubleClick($listbox1_MouseDoubleClick)
$buttonOK.Anchor = 'Bottom, Right'
$buttonOK.DialogResult = 'OK'
$buttonOK.Location = '291, 353'
$buttonOK.Name = 'buttonOK'
$buttonOK.Size = '75, 23'
$buttonOK.TabIndex = 0
$buttonOK.Text = '&OK'
$form1.ShowDialog()
Or even this using just the ComboBox elements
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$Form.ClientSize = New-Object System.Drawing.Point(498,459)
$Form.text = 'Form'
$Form.TopMost = $false
$Form.StartPosition = 'CenterScreen'
$ComboBox1 = New-Object system.Windows.Forms.ComboBox
$ComboBox1.text = ''
$ComboBox1.width = 216
$ComboBox1.height = 75
#('ComboxItem1','ComboxItem2','ComboxItem3') |
ForEach-Object {[void] $ComboBox1.Items.Add($_)}
$ComboBox1.location = New-Object System.Drawing.Point(31,41)
$ComboBox1.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$ComboBox2 = New-Object system.Windows.Forms.ComboBox
$ComboBox2.text = ''
$ComboBox2.width = 213
$ComboBox2.height = 38
$ComboBox2.location = New-Object System.Drawing.Point(32,73)
$ComboBox2.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
Function Add-ItemToComboBox2
{
$ComboBox2.Items.Add($ComboBox1.SelectedItem)
$ComboBox2.Refresh()
}
$Form.controls.AddRange(
#(
$ComboBox1,
$ComboBox2
)
)
$ComboBox1.Add_SelectedIndexChanged({ Add-ItemToComboBox2 })
[void]$Form.ShowDialog()
You have not stated what UX/UI tool you are using to design and implement your
GUI. Yet, hard coding is also just a challenge. So consider using one of these for your UX/UI effort. Your UX/UI should just work, whether you have PowerShell code behind it (or any other language). Your PowerShell code should just work, regardless of the UX/UI that may be implemented. Your UX/UI code should be separate from your ops code. You call your ops code from the UX/UI.
Free:
https://poshgui.com
https://www.youtube.com/results?search_query=poshgui
https://visualstudio.microsoft.com/vs/community
Be sure to thoroughly read the licensing agreement for VS.
https://www.youtube.com/results?search_query=vs+2019+community+winforms
Purchase
https://ironmansoftware.com/psscriptpad
https://www.youtube.com/results?search_query=psscriptpad
https://ironmansoftware.com/powershell-pro-tools
https://www.youtube.com/results?search_query=powershell-pro-tools
https://www.sapien.com/software/powershell_studio
https://www.youtube.com/results?search_query=Sapien%27s+powershell+studio++winforms
https://visualstudio.microsoft.com/vs
https://www.youtube.com/results?search_query=vs+2019+community+winforms

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
}

PS Forms - Unhandled Exception using BREAK in ForEach loop

Following on from a previous question
The actual code is a lot more complex, but the following is working example of my loop:
Add-Type -AssemblyName System.Windows.Forms
$source = '\\servera\files'
$destination = '\\server b\files'
$form = New-Object System.Windows.Forms.Form
$CopyOutput = New-Object System.Windows.Forms.Label
$CopyOutput.Location = '10,15'
$CopyOutput.Size = '350,20'
$form.Text = "$DomainName Folder/Archive Copy"
$form.Size = '380,130'
$form.CancelButton = $ExitButton
$form.Add_FormClosing({
$script:CancelLoop = $true
})
$StartButton = New-Object System.Windows.Forms.Button
$StartButton.Name = 'StartButton'
$StartButton.Location = '10,50'
$StartButton.Size = '75,23'
$StartButton.Text = 'Start Copy'
$StartButton.Enabled = $true
$PauseButton = New-Object System.Windows.Forms.Button
$PauseButton.Location = '100,50'
$PauseButton.Size = '75,23'
$PauseButton.Text = 'Pause Copy'
$PauseButton.Enabled = $true
$StopButton = New-Object System.Windows.Forms.Button
$StopButton.Location = '190,50'
$StopButton.Size = '75,23'
$StopButton.Text = 'Stop Copy'
$StopButton.Enabled = $true
$ExitButton = New-Object System.Windows.Forms.Button
$ExitButton.Name = 'ExitButton'
$ExitButton.Location = '280,50'
$ExitButton.Size = '75,23'
$ExitButton.Text = 'Exit'
$ExitButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.Controls.AddRange(#($StartButton,$PauseButton,$StopButton,$ExitButton,$CopyOutput))
$StopButton.Add_Click({
$script:PauseToggle = $false
$script:CancelLoop = $true
})
$PauseButton.Add_Click({
# Boolean change value to true/false
$script:PauseToggle = !$script:PauseToggle
})
$StartButton.Add_Click({
$script:CancelLoop = $false
$script:PauseToggle = $false
$StopButton.Enabled = $true
$StartButton.Enabled = $false
Get-ChildItem -LiteralPath $Source -Recurse -File | ForEach {
Copy-Item -LiteralPath $_.FullName -Destination $Destination
$CopyOutput.Text = ('Copying' + $_.FullName)
[System.Windows.Forms.Application]::DoEvents()
If($script:CancelLoop -eq $true) {
$CopyOutput.Text = 'Cancel copy'
#Exit the loop
Break;
}
If ($script:PauseToggle) {
$CopyOutput.Text = 'Paused'
Do {
[System.Windows.Forms.Application]::DoEvents()
} Until (!$script:PauseToggle)
}
}
$CancelButton.Enabled = $false
$StartCopyButton.Enabled = $true
})
$form.ShowDialog()
$form.Dispose()
All the articles I can find say that this code should work ok - can anyone advise how to avoid the unhandled exception which results when the "Stop" button is pressed?
All the articles I can find say that this code should work ok - can anyone advise how to avoid the unhandled exception which results when the "Stop" button is pressed?
From what I can see in my research, this is an issue with using BREAK in forms. I did however find a workaround from here
Using this commandlet will stop the current pipeline instead of using BREAK
Filter Stop-Pipeline {
$sp = { Select-Object -First 1 }.GetSteppablePipeline($MyInvocation.CommandOrigin)
$sp.Begin($true)
$sp.Process(0)
}