Can't display groupbox in my Powershell GUI - powershell

I don't understand why my GroupBox isn't displayed.
I would like to display groupbox with several labels but it doesn't work.
I've tried to replace the radiobuttons by labels with the code here => https://sysadminemporium.wordpress.com/2012/12/07/powershell-gui-for-your-scripts-episode-3/
I'm a beginner in GUI and I have seen other examples but I can't use this code as I would like.
Here is my code :
#----------------------------------------------
# Generated Form Function
#----------------------------------------------
function Call-test_psf {
#----------------------------------------------
#region Import the Assemblies
#----------------------------------------------
[void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
#endregion Import Assemblies
#----------------------------------------------
#region Generated Form Objects
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$form1.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedDialog
$form1.MaximizeBox = $False
$form1.MinimizeBox = $False
# Choix du titre
$form1.Text = "Title"
$label4 = New-Object 'System.Windows.Forms.Label'
$label5 = New-Object 'System.Windows.Forms.Label'
#endregion Generated Form Objects
#----------------------------------------------
# User Generated Script
#----------------------------------------------
$form1_Load={
#TODO: Initialize Form Controls here
}
# --End User Generated Script--
#----------------------------------------------
#region Generated Events
#----------------------------------------------
$Form_StateCorrection_Load=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
$Form_Cleanup_FormClosed=
{
#Remove all event handlers from the controls
try
{
$buttonSuivant.remove_Click($buttonSuivant_Click)
$buttonRetour.remove_Click($buttonRetour_Click)
$form1.remove_Load($form1_Load)
$form1.remove_Load($Form_StateCorrection_Load)
$form1.remove_FormClosed($Form_Cleanup_FormClosed)
}
catch [Exception]
{ }
}
#endregion Generated Events
#----------------------------------------------
#region Generated Form Code
#----------------------------------------------
$form1.SuspendLayout()
#
# form1
#
$form1.Controls.Add($groupBox1)
$form1.ClientSize = '700, 300'
#endregion
$form1.Name = 'form1'
$form1.Text = 'Title'
$form1.add_Load($form1_Load)
#
# GroupBox1
#
$groupBox1 = New-Object System.Windows.Forms.GroupBox
$groupBox1.Location = '150,300'
$groupBox1.size = '400,150'
$groupBox1.text = "Title groupBox1"
$groupBox1.Visible = $true
#
# progressBar1
#
$progressBar1 = New-Object System.Windows.Forms.ProgressBar
$progressBar1.Name = 'progressBar1'
$progressBar1.Value = 0
$progressBar1.Style="Continuous"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = $width - 40
$System_Drawing_Size.Height = 20
$progressBar1.Size = $System_Drawing_Size
$progressBar1.Left = 5
$progressBar1.Top = 40
#
# label4
#
$label4.Font = 'Microsoft Sans Serif, 8pt'
$label4.Location = '50, 50'
$label4.Name = 'label2'
$label4.Size = '20, 20'
$label4.TabIndex = 8
$label4.TextAlign = 'TopLeft'
$label4.Visible = $false
$label4.Text = "test"
#
# label5
#
$label5.Font = 'Microsoft Sans Serif, 8pt'
$label5.Location = '50, 70'
$label5.Name = 'label2'
$label5.Size = '20, 20'
$label5.TabIndex = 10
$label5.TextAlign = 'TopLeft'
$label5.Visible = $false
$label5.Text = "test"
$groupBox1.Controls.AddRange(#($Label4,$Label5))
#
$form1.ResumeLayout()
#endregion Generated Form Code
#----------------------------------------------
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($Form_StateCorrection_Load)
#Clean up the control events
$form1.add_FormClosed($Form_Cleanup_FormClosed)
#Show the Form
return $form1.ShowDialog()
} #End Function
#Call the form
Call-test_psf | Out-Null
Can you help me ?
Thank you in advance.

Change 2 lines:
$groupBox1.Location = '150,300'
y location is 300, which is off the bottom of your form as it's only 300px high.
$form1.Controls.Add($groupBox1)
Move this line to after you have created the groupbox. So anywhere after $groupBox1 = New-Object System.Windows.Forms.GroupBox
For example:
$groupBox1 = New-Object System.Windows.Forms.GroupBox
$groupBox1.Location = '10,10'
$groupBox1.size = '400,150'
$groupBox1.text = "Title groupBox1"
$groupBox1.Visible = $true
$form1.Controls.Add($groupBox1) # line moved here.

Related

Getting keypress on a Form in Powershell

Im trying to make a image viewer in powershell using some windows forms libraries, I can already store the images location inside an array, but now I want it to detect the keys Right and Left to change between the locations inside the array
Here is the code I'm using:
param(
[parameter (Mandatory=$false, position=0, ParameterSetName='url')]
[string]$url = ''
)
Add-Type -AssemblyName 'System.Windows.Forms'
[void][reflection.assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Windows.Forms.Application]::EnableVisualStyles()
Function Load-Images{
param (
[parameter (Mandatory=$true, position=0, ParameterSetName='path')]
$path
)
$screen = [System.Windows.Forms.Screen]::AllScreens
$form = new-object Windows.Forms.Form
$form.Text = "Image Viewer"
$form.Size = New-Object System.Drawing.Size($screen.WorkingArea[0].Width, $screen.WorkingArea[0].Height)
$pictureBox = new-object Windows.Forms.PictureBox
$pictureBox.Size = New-Object System.Drawing.Size($screen.WorkingArea[0].Width, $screen.WorkingArea[0].Height)
$pictureBox.Image = $path
$pictureBox.SizeMode = 'Zoom'
$pictureBox.Anchor = 'Top,Left,Bottom,Right'
$form.controls.add($pictureBox)
$form.Add_Shown( { $form.Activate() } )
$form.ShowDialog()
$img.dispose()
}
if(!$url) {
$dir = Get-Location
$Files = #(Get-ChildItem "$($dir.Path)\*" -Include *.jpg, *.jpeg, *.png)
$maxSize = $Files.Length
Write-Output $maxSize
Write-Output $Files.Fullname
$img = [System.Drawing.Image]::Fromfile((Get-Item $Files.Fullname[0]))
Load-Images -path $img
}
Continuing from my comment. What you are after is not specific to PowerShell at all. It's a UX/UI design/property/event item.
For Example, here is one showing adding and using the property/event setting to watch for defined keypresses. Just run the function, call the function, and hit 'Enter' or 'Esc', or click 'OK' to fire those events.
function Start-CreateForm
{
#Import Assemblies
Add-Type -AssemblyName System.Windows.Forms,
System.Drawing
$Form1 = New-Object System.Windows.Forms.Form
$OKButton = New-Object System.Windows.Forms.Button
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
$Label1 = New-Object System.Windows.Forms.Label
$textBox1 = New-Object System.Windows.Forms.TextBox
$Field1 = ""
# Check for ENTER and ESC presses
$Form1.KeyPreview = $True
$Form1.Add_KeyDown({if ($PSItem.KeyCode -eq "Enter")
{
# if enter, perform click
$OKButton.PerformClick()
}
})
$Form1.Add_KeyDown({if ($PSItem.KeyCode -eq "Escape")
{
# if escape, exit
$Form1.Close()
}
})
# The action on the button
$handler_OK_Button_Click=
{
$Field1 = $textBox1.Text
$Field1
# Returns a message of no data
if ($Field1 -eq "") {[System.Windows.Forms.MessageBox]::Show("You didn't enter anything!", "Data")}
# Returns what they types. You could add your code here
else {[System.Windows.Forms.MessageBox]::Show($Field1, "Data")}
}
$OnLoadForm_StateCorrection=
{
$Form1.WindowState = $InitialFormWindowState
}
# Form Code
$Form1.Name = "Data_Form"
$Form1.Text = "Data Form"
$Form1.MaximizeBox = $false #lock form
$Form1.FormBorderStyle = 'Fixed3D'
# None,FixedDialog,FixedSingle,FixedToolWindow,Sizable,SizableToolWindow
# Icon
$Form1.Icon = [Drawing.Icon]::ExtractAssociatedIcon((Get-Command powershell).Path)
# $NotifyIcon.Icon = [Drawing.Icon]::ExtractAssociatedIcon((Get-Command powershell).Path)
$Form1.DataBindings.DefaultDataSourceUpdateMode = 0
$Form1.StartPosition = "CenterScreen"# moves form to center of screen
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 300 # sets X
$System_Drawing_Size.Height = 150 # sets Y
$Form1.ClientSize = $System_Drawing_Size
$OKButton.Name = "OK_Button"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 45
$System_Drawing_Size.Height = 23
$OKButton.Size = $System_Drawing_Size
$OKButton.UseVisualStyleBackColor = $True
$OKButton.Text = "OK"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 113
$OKButton.Location = $System_Drawing_Point
$OKButton.DataBindings.DefaultDataSourceUpdateMode = 0
$OKButton.add_Click($handler_OK_Button_Click)
$Form1.Controls.Add($OKButton)
$InitialFormWindowState = $Form1.WindowState
$Form1.add_Load($OnLoadForm_StateCorrection)
$Label1.Location = New-Object System.Drawing.Point(10,20)
$Label1.Size = New-Object System.Drawing.Size(280,20)
$Label1.Text = "Enter data here:"
$Form1.Controls.Add($Label1)
$textBox1.TabIndex = 0 # Places cursor in field
$textBox1.Location = New-Object System.Drawing.Point(10,40)
$textBox1.Size = New-Object System.Drawing.Size(260,20)
$Form1.Controls.Add($textBox1)
$Form1.Topmost = $True # Moves form to top and stays on top
$Form1.Add_Shown({$textBox1.Select()})
# Show Form
$Form1.ShowDialog()
}
For your use case, you just have to use the needed keyboard specifics.

How do I return errorlevel by handling GUI using PowerShell?

I have a GUI, the form will close automatically in 10s. But if we click the pause button, it also will close the form. I want to return the error level each process that I do. If the form closes automatically, it will return error level 10. but if we click the button pause, it will return error level 20. anyone can help, please.
this is my code.
function Timer_GUI {
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$label1 = New-Object 'System.Windows.Forms.Label'
$label2 = New-Object 'System.Windows.Forms.Label'
$Cancel = New-Object 'System.Windows.Forms.Button'
$timer1 = New-Object 'System.Windows.Forms.Timer'
$form1_Load = {
$TotalTime = 10 #in seconds
$script:StartTime = (Get-Date).AddSeconds($TotalTime)
#Start the timer
$timer1.Start()
}
$label1.Location = New-Object System.Drawing.Size(220,60)
$label1.Size = New-Object System.Drawing.Size(500,30)
$label2.Text = "The Process Will Continue in 10s"
$label2.Location = New-Object System.Drawing.Size(140,30)
$label2.Size = New-Object System.Drawing.Size(500,30)
$form1.SuspendLayout()
$form1.Controls.Add($label1)
$form1.Controls.Add($label2)
$form1.Controls.Add($Cancel)
$form1.Width = 500
$form1.Height = 200
$form1.StartPosition = "CenterScreen"
$form1.BackColor = "#e2e2e2"
$form1.add_Load($form1_Load)
$Cancel.DialogResult = 'Cancel'
$Cancel.Location = New-Object System.Drawing.Size(350,100)
$Cancel.Size = New-Object System.Drawing.Size(100,30)
$Cancel.Text = "Pause"
$Cancel.add_Click($Cancel_Click)
$timer1.add_Tick($timer1_Tick)
$form1.ResumeLayout()
#Show the Form
return $form1.ShowDialog()
exit 100
}
#Call the form
Timer_GUI | Out-Null
Not a GUI expert, but, here it is. Add a global variable $Global:formresult default set to 10, if button clicked set to 20.
The following 3 lines added or updated,
Add-Type -AssemblyName System.Windows.Forms
$Global:formresult = 10
$Cancel.add_Click({ $Global:formresult = 20 })
$Global:formresult
Full code, copy and paste from yours.
Add-Type -AssemblyName System.Windows.Forms
function Timer_GUI {
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$label1 = New-Object 'System.Windows.Forms.Label'
$label2 = New-Object 'System.Windows.Forms.Label'
$Cancel = New-Object 'System.Windows.Forms.Button'
$timer1 = New-Object 'System.Windows.Forms.Timer'
$Global:formresult = 10
$form1_Load = {
$TotalTime = 10 #in seconds
$script:StartTime = (Get-Date).AddSeconds($TotalTime)
#Start the timer
$timer1.Start()
}
$label1.Location = New-Object System.Drawing.Size(220,60)
$label1.Size = New-Object System.Drawing.Size(500,30)
$label2.Text = "The Process Will Continue in 10s"
$label2.Location = New-Object System.Drawing.Size(140,30)
$label2.Size = New-Object System.Drawing.Size(500,30)
$form1.SuspendLayout()
$form1.Controls.Add($label1)
$form1.Controls.Add($label2)
$form1.Controls.Add($Cancel)
$form1.Width = 500
$form1.Height = 200
$form1.StartPosition = "CenterScreen"
$form1.BackColor = "#e2e2e2"
$form1.add_Load($form1_Load)
$Cancel.DialogResult = 'Cancel'
$Cancel.Location = New-Object System.Drawing.Size(350,100)
$Cancel.Size = New-Object System.Drawing.Size(100,30)
$Cancel.Text = "Pause"
$Cancel.add_Click({ $Global:formresult = 20 })
$timer1.add_Tick($timer1_Tick)
$form1.ResumeLayout()
#Show the Form
return $form1.ShowDialog()
exit 100
}
#Call the form
Timer_GUI | Out-Null
$Global:formresult

PowerShell Form Data Output To JSON Format

The following GIF image is an example of a dialog written use the C# programming language, which contains four controls!
Now, I want to use PowerShell to achieve the same functionality, I made the following design (such as the first dialog in the GIF picture):
The first control, the ID name is Input
The second control, the ID name is MultipleSelect
The third control, the ID name is InlineRadioOption
The fourth control, the ID name is Checkbox
When I click the OK button, I want to output the values ​​of all the controls to a JSON format object, for example: $CustomDialogResults
Later, I can get the value of each control in the following way (such as the second message box in the GIF image):
$CustomDialogResults.Input
$CustomDialogResults.MultipleSelect
$CustomDialogResults.InlineRadioOption
$CustomDialogResults.Checkbox
I want to know how to express objects in JSON format?
function Show-dialog_psf {
[void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
#endregion Import Assemblies
#----------------------------------------------
#region Generated Form Objects
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$labelInlinRadios = New-Object 'System.Windows.Forms.Label'
$panel1 = New-Object 'System.Windows.Forms.Panel'
$radiobuttonRadioOption3 = New-Object 'System.Windows.Forms.RadioButton'
$radiobuttonRadioOption1 = New-Object 'System.Windows.Forms.RadioButton'
$radiobuttonRadioOption2 = New-Object 'System.Windows.Forms.RadioButton'
$Checkbox = New-Object 'System.Windows.Forms.CheckBox'
$MultipleSelect = New-Object 'System.Windows.Forms.CheckedListBox'
$labelMultipleSelect = New-Object 'System.Windows.Forms.Label'
$input = New-Object 'System.Windows.Forms.TextBox'
$labelInput = New-Object 'System.Windows.Forms.Label'
$buttonOK = New-Object 'System.Windows.Forms.Button'
$InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
#endregion Generated Form Objects
#----------------------------------------------
# User Generated Script
#----------------------------------------------
$form1_Load = {
#TODO: Initialize Form Controls here
}
$buttonOK_Click = {
$CustomDialogResults = #{
#$CustomDialogResults.Input,
#$CustomDialogResults.MultipleSelect,
#$CustomDialogResults.InlineRadioOption,
#$CustomDialogResults.Checkbox,
}
[void][System.Windows.Forms.MessageBox]::Show($CustomDialogResults, 'Title') # Casting the method to [void] suppresses the output.
}
# --End User Generated Script--
#----------------------------------------------
#region Generated Events
#----------------------------------------------
$Form_StateCorrection_Load=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
$Form_Cleanup_FormClosed=
{
#Remove all event handlers from the controls
try
{
$buttonOK.remove_Click($buttonOK_Click)
$form1.remove_Load($form1_Load)
$form1.remove_Load($Form_StateCorrection_Load)
$form1.remove_FormClosed($Form_Cleanup_FormClosed)
}
catch { Out-Null <# Prevent PSScriptAnalyzer warning #> }
}
#endregion Generated Events
#----------------------------------------------
#region Generated Form Code
#----------------------------------------------
$form1.SuspendLayout()
$panel1.SuspendLayout()
#
# form1
#
$form1.Controls.Add($labelInlinRadios)
$form1.Controls.Add($panel1)
$form1.Controls.Add($Checkbox)
$form1.Controls.Add($MultipleSelect)
$form1.Controls.Add($labelMultipleSelect)
$form1.Controls.Add($input)
$form1.Controls.Add($labelInput)
$form1.Controls.Add($buttonOK)
$form1.AcceptButton = $buttonOK
$form1.AutoScaleDimensions = '6, 13'
$form1.AutoScaleMode = 'Font'
$form1.ClientSize = '436, 288'
$form1.FormBorderStyle = 'FixedDialog'
$form1.MaximizeBox = $False
$form1.MinimizeBox = $False
$form1.Name = 'form1'
$form1.StartPosition = 'CenterScreen'
$form1.Text = 'Form'
$form1.add_Load($form1_Load)
#
# labelInlinRadios
#
$labelInlinRadios.AutoSize = $True
$labelInlinRadios.Location = '21, 172'
$labelInlinRadios.Name = 'labelInlinRadios'
$labelInlinRadios.Size = '63, 17'
$labelInlinRadios.TabIndex = 10
$labelInlinRadios.Text = 'Inlin Radios'
$labelInlinRadios.UseCompatibleTextRendering = $True
#
# panel1
#
$panel1.Controls.Add($radiobuttonRadioOption3)
$panel1.Controls.Add($radiobuttonRadioOption1)
$panel1.Controls.Add($radiobuttonRadioOption2)
$panel1.AutoSize = $True
$panel1.Location = '95, 162'
$panel1.Name = 'panel1'
$panel1.Size = '329, 32'
$panel1.TabIndex = 9
#
# radiobuttonRadioOption3
#
$radiobuttonRadioOption3.Location = '217, 5'
$radiobuttonRadioOption3.Name = 'radiobuttonRadioOption3'
$radiobuttonRadioOption3.Size = '105, 24'
$radiobuttonRadioOption3.TabIndex = 7
$radiobuttonRadioOption3.TabStop = $True
$radiobuttonRadioOption3.Text = 'Radio option3'
$radiobuttonRadioOption3.UseCompatibleTextRendering = $True
$radiobuttonRadioOption3.UseVisualStyleBackColor = $True
#
# radiobuttonRadioOption1
#
$radiobuttonRadioOption1.Location = '7, 4'
$radiobuttonRadioOption1.Name = 'radiobuttonRadioOption1'
$radiobuttonRadioOption1.Size = '105, 24'
$radiobuttonRadioOption1.TabIndex = 5
$radiobuttonRadioOption1.TabStop = $True
$radiobuttonRadioOption1.Text = 'Radio option1'
$radiobuttonRadioOption1.UseCompatibleTextRendering = $True
$radiobuttonRadioOption1.UseVisualStyleBackColor = $True
#
# radiobuttonRadioOption2
#
$radiobuttonRadioOption2.Location = '112, 4'
$radiobuttonRadioOption2.Name = 'radiobuttonRadioOption2'
$radiobuttonRadioOption2.Size = '105, 24'
$radiobuttonRadioOption2.TabIndex = 6
$radiobuttonRadioOption2.TabStop = $True
$radiobuttonRadioOption2.Text = 'Radio option2'
$radiobuttonRadioOption2.UseCompatibleTextRendering = $True
$radiobuttonRadioOption2.UseVisualStyleBackColor = $True
#
# Checkbox
#
$Checkbox.Location = '102, 200'
$Checkbox.Name = 'Checkbox'
$Checkbox.Size = '104, 24'
$Checkbox.TabIndex = 8
$Checkbox.Text = 'checkbox1'
$Checkbox.UseCompatibleTextRendering = $True
$Checkbox.UseVisualStyleBackColor = $True
#
# MultipleSelect
#
$MultipleSelect.CheckOnClick = $True
$MultipleSelect.FormattingEnabled = $True
[void]$MultipleSelect.Items.Add('Multiple Select option1')
[void]$MultipleSelect.Items.Add('Multiple Select option2')
[void]$MultipleSelect.Items.Add('Multiple Select option3')
$MultipleSelect.Location = '121, 68'
$MultipleSelect.Name = 'MultipleSelect'
$MultipleSelect.Size = '277, 79'
$MultipleSelect.TabIndex = 4
$MultipleSelect.UseCompatibleTextRendering = $True
#
# labelMultipleSelect
#
$labelMultipleSelect.AutoSize = $True
$labelMultipleSelect.Location = '27, 68'
$labelMultipleSelect.Name = 'labelMultipleSelect'
$labelMultipleSelect.Size = '78, 17'
$labelMultipleSelect.TabIndex = 3
$labelMultipleSelect.Text = 'Multiple Select'
$labelMultipleSelect.UseCompatibleTextRendering = $True
#
# input
#
$input.Location = '121, 31'
$input.Name = 'input'
$input.Size = '277, 20'
$input.TabIndex = 2
$input.Text = 'input text'
#
# labelInput
#
$labelInput.AutoSize = $True
$labelInput.Location = '76, 34'
$labelInput.Name = 'labelInput'
$labelInput.Size = '29, 17'
$labelInput.TabIndex = 1
$labelInput.Text = 'Input'
$labelInput.UseCompatibleTextRendering = $True
#
# buttonOK
#
$buttonOK.Anchor = 'Bottom, Right'
$buttonOK.DialogResult = 'OK'
$buttonOK.Location = '349, 253'
$buttonOK.Name = 'buttonOK'
$buttonOK.Size = '75, 23'
$buttonOK.TabIndex = 0
$buttonOK.Text = '&OK'
$buttonOK.UseCompatibleTextRendering = $True
$buttonOK.UseVisualStyleBackColor = $True
$buttonOK.add_Click($buttonOK_Click)
$panel1.ResumeLayout()
$form1.ResumeLayout()
#endregion Generated Form Code
#----------------------------------------------
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($Form_StateCorrection_Load)
#Clean up the control events
$form1.add_FormClosed($Form_Cleanup_FormClosed)
#Show the Form
return $form1.ShowDialog()
} #End Function
#Call the form
Show-dialog_psf | Out-Null
Change your buttonOk click function to get desire output :
Note : This is the sample json, you have yo replace the hard-coded string with your actual values | objects.
$buttonOK_Click = {
$CustomDialogResults = #{}
$CustomDialogResults.Add("Input",$txtinput.Text)
$CustomDialogResults.Add("MultipleSelect",$MultipleSelect.CheckedItems)
$CustomDialogResults.Add("Checkbox", $Checkbox.Checked)
$selectedradio = $null ;
switch($True)
{
$($radiobuttonRadioOption1.Checked){
$selectedradio = $radiobuttonRadioOption1.Text ;
}
$($radiobuttonRadioOption2.Checked){
$selectedradio = $radiobuttonRadioOption2.Text ;
}
$($radiobuttonRadioOption3.Checked){
$selectedradio = $radiobuttonRadioOption3.Text ;
}
}
$CustomDialogResults.Add("InlineRadioOption",$selectedradio)
$temp = ConvertTo-Json -InputObject $CustomDialogResults
[void][System.Windows.Forms.MessageBox]::Show($temp, 'Title')
}
I would do something like this in ur ButtonOk_click eventhandler.
function Get-RadioButtonCheck
{
#if-else logic
#returns which Radio button is checked
$CheckedRadioButton = "RadioButton1" #as an example
Return $CheckedRadioButton
}
$CustomDialogResults = [PSCustomObject]#{
Input = $($input.Text)
MultipleSelect = $($MultipleSelect.SelectedItems)
InlineRadioOption = Get-RadioButtonCheck
Checkbox = $($Checkbox.Checked)
}
$JSONdata = $CustomDialogResults | ConvertTo-Json
#Now you can output this $JSONdata to a file or text box or even a Messagebox like u are already doing

Update ComboBox Once item is selected

I'm lost and could really use some help. I'm trying to update a combo box with a list of column names from a csv file (selected by the open file button, and string input into textbox).
Function GetFileName($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "CSV (*.csv)| *.csv"
$OpenFileDialog.multiselect = $false
$OpenFileDialog.ShowDialog() | Out-Null
return $OpenFileDialog.FileName
}
Function GetColumnsFromFile
{
Param ($fileWithPath)
[string]$csvFileColumnTitles = Get-Content $fileWithPath -totalcount 1
[String[]]$csvFileColumnTitles = ($csvFileColumnTitles -replace ",", "|").Trim()
[String[]]$csvFileColumnTitles = ($csvFileColumnTitles -replace "`"", "").Trim()
[String[]]$listOfColumnTitles = $csvFileColumnTitles.Split('|',[System.StringSplitOptions]::RemoveEmptyEntries)
return $listOfColumnTitles
}
Function GUIBox
{
# Creates GUI Box In Memory
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.drawing
$Form = New-Object system.Windows.Forms.Form
$Form.Width = '1200'
$Form.Height = '800'
# TabControl
$TabControl = New-Object System.Windows.Forms.TabControl
$TabControl.Name = "TabControl"
$TabControl.TabIndex = 4
$TabControl.SelectedIndex = 0
$TabControl.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 0
$System_Drawing_Point.Y = 50
$TabControl.Location = $System_Drawing_Point
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 685
$System_Drawing_Size.Width = 1184
$TabControl.Size = $System_Drawing_Size
$Form.Controls.Add($TabControl)
# Test 1 Tab
$Test1_Tab = New-Object System.Windows.Forms.TabPage
$Test1_Tab.DataBindings.DefaultDataSourceUpdateMode = 0
$Test1_Tab.Name = "Test 1"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 0
$System_Drawing_Point.Y = 50
$Test1_Tab.Location = $System_Drawing_Point
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 685
$System_Drawing_Size.Width = 1184
$Test1_Tab.Size = $System_Drawing_Size
$Test1_Tab.TabIndex = 1
$Test1_Tab.Text = "Test 1"
$Test1_Tab.UseVisualStyleBackColor = $True
$TabControl.Controls.Add($Test1_Tab)
# Open File Label
$SelectSourceFile_Label = New-Object System.Windows.Forms.Label
$SelectSourceFile_Label.Location = "10, 30"
$SelectSourceFile_Label.Name = "label"
$SelectSourceFile_Label.Size = "120, 20"
$SelectSourceFile_Label.TabIndex = 3
$SelectSourceFile_Label.Text = "Select Source File"
$Test1_Tab.Controls.Add($SelectSourceFile_Label)
# Open File Textbox
$SelectSourceFile_Textbox = New-Object System.Windows.Forms.TextBox
$SelectSourceFile_Textbox.Location = '10, 50'
$SelectSourceFile_Textbox.Size = '200, 20'
$SelectSourceFile_Textbox.TabIndex = 3
$SelectSourceFile_Textbox.Text = $Test1_FileInput_Textbox_String
$Test1_Tab.Controls.Add($SelectSourceFile_Textbox)
# Open File Button
$SelectSourceFile_Button = New-Object System.Windows.Forms.Button
$SelectSourceFile_Button.DialogResult = 'None'
$SelectSourceFile_Button.Location = '210, 50'
$SelectSourceFile_Button.Name = 'Open File Button'
$SelectSourceFile_Button.Size = '75, 25'
$SelectSourceFile_Button.TabIndex = 3
$SelectSourceFile_Button.Text = 'Open File'
$SelectSourceFile_Button.UseVisualStyleBackColor = $true
$SelectSourceFile_Button_Click = {$SelectSourceFile_Textbox.Text = GetFileName}
$SelectSourceFile_Button.add_Click($SelectSourceFile_Button_Click)
$Test1_Tab.Controls.Add($SelectSourceFile_Button)
# Select Open File Columns Label
$SelectSourceFileColumn_Label = New-Object System.Windows.Forms.Label
$SelectSourceFileColumn_Label.Location = "10, 90"
$SelectSourceFileColumn_Label.Name = "label"
$SelectSourceFileColumn_Label.Size = "150, 20"
$SelectSourceFileColumn_Label.TabIndex = 3
$SelectSourceFileColumn_Label.Text = "Select Source File Column"
$Test1_Tab.Controls.Add($SelectSourceFileColumn_Label)
# Select Open File Columns Dropdown
[String[]]$ColumnList = GetColumnsFromFile 'C:\Scripts\Tests\1Project\Test.csv'
Write-Host '$ColumnList =' $ColumnList
$SelectSourceFileColumn_Dropdown = New-Object 'System.Windows.Forms.ComboBox'
$SelectSourceFileColumn_Dropdown.FormattingEnabled = $True
$SelectSourceFileColumn_Dropdown.Location = '10, 110'
$SelectSourceFileColumn_Dropdown.Name = 'File Column'
$SelectSourceFileColumn_Dropdown.Size = '200, 20'
$SelectSourceFileColumn_Dropdown.TabIndex = 3
$SelectSourceFileColumn_Dropdown.Height = 30
$Test1_Tab.Controls.Add($SelectSourceFileColumn_Dropdown)
## Display GUI Box ##
$Form.ShowDialog()
}
GUIBox
The csv file...
"ColumnOne","ColumnTwo","ColumnThree"
"ColumnOneValueOne","ColumnTwoValueOne","ColumnThreeValueOne"
"ColumnOneValueTwo","ColumnTwoValueTwo","ColumnThreeValueTwo"
"ColumnOneValueThree","ColumnTwoValueThree","ColumnThreeValueThree"
So in the powershell window, we can see it is able to print the 3 column names. I know if I try this line [String[]]$ColumnList = GetColumnsFromFile $SelectSourceFile_Textbox.Text (replacing line 110), it will error out (because it will iterate through this line, before the user has a chance to input the selected file). So how would I update the combobox (with column names from the csv file) after the user has input their csv file?
One way you could do this is to use the button click to show the FolderBrowserDialog and if you get a filename from it, get the headings and add each one to the combobox.
You can use the same technique to populate the ComboBox when the user types into the textbox by creating a TextChanged event.
I got this to work using the following code:
function GUIBox {
#----------------------------------------------
#region Import the Assemblies
#----------------------------------------------
[void][reflection.assembly]::Load('System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][reflection.assembly]::Load('System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][reflection.assembly]::Load('System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
#endregion Import Assemblies
#----------------------------------------------
#region Generated Form Objects
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$textbox1 = New-Object 'System.Windows.Forms.TextBox'
$combobox1 = New-Object 'System.Windows.Forms.ComboBox'
$buttonLoadCsv = New-Object 'System.Windows.Forms.Button'
$InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
#endregion Generated Form Objects
#----------------------------------------------
# User Generated Script
#----------------------------------------------
function Get-FileName($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "CSV (*.csv)| *.csv"
$OpenFileDialog.multiselect = $false
$OpenFileDialog.ShowDialog() | Out-Null
return $OpenFileDialog.FileName
}
$form1_Load={
#TODO: Initialize Form Controls here
}
$buttonLoadCsv_Click={
#TODO: Place custom script here
$file = Get-FileName -initialDirectory $env:USERPROFILE
if ($file)
{
$textbox1.Text = $file
try
{
$headers = Import-Csv -Path $file | Get-Member | Where-Object -FilterScript {$_.MemberType -eq 'NoteProperty'} | Select-Object -ExpandProperty Name -Unique
Write-Host ($headers | Out-String)
$combobox1.Items.Clear()
foreach($header in $headers)
{
$combobox1.Items.Add($header)
}
}
catch
{
Write-Warning -Message "The following error occured while trying to get the headings for csv file $file`: $($_.Exception.Message)"
}
}
}
# --End User Generated Script--
#----------------------------------------------
#region Generated Events
#----------------------------------------------
$Form_StateCorrection_Load=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
$Form_Cleanup_FormClosed=
{
#Remove all event handlers from the controls
try
{
$buttonLoadCsv.remove_Click($buttonLoadCsv_Click)
$form1.remove_Load($form1_Load)
$form1.remove_Load($Form_StateCorrection_Load)
$form1.remove_FormClosed($Form_Cleanup_FormClosed)
}
catch [Exception]
{ }
}
#endregion Generated Events
#----------------------------------------------
#region Generated Form Code
#----------------------------------------------
$form1.SuspendLayout()
#
# form1
#
$form1.Controls.Add($textbox1)
$form1.Controls.Add($combobox1)
$form1.Controls.Add($buttonLoadCsv)
$form1.ClientSize = '390, 76'
$form1.Name = 'form1'
$form1.Text = 'Form'
$form1.add_Load($form1_Load)
#
# textbox1
#
$textbox1.Location = '12, 14'
$textbox1.Name = 'textbox1'
$textbox1.Size = '284, 20'
$textbox1.TabIndex = 2
#
# combobox1
#
$combobox1.DropDownStyle = 'DropDownList'
$combobox1.FormattingEnabled = $True
$combobox1.Location = '12, 40'
$combobox1.Name = 'combobox1'
$combobox1.Size = '284, 21'
$combobox1.TabIndex = 1
#
# buttonLoadCsv
#
$buttonLoadCsv.Location = '302, 12'
$buttonLoadCsv.Name = 'buttonLoadCsv'
$buttonLoadCsv.Size = '75, 49'
$buttonLoadCsv.TabIndex = 0
$buttonLoadCsv.Text = 'Load Csv'
$buttonLoadCsv.UseVisualStyleBackColor = $True
$buttonLoadCsv.add_Click($buttonLoadCsv_Click)
$form1.ResumeLayout()
#endregion Generated Form Code
#----------------------------------------------
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($Form_StateCorrection_Load)
#Clean up the control events
$form1.add_FormClosed($Form_Cleanup_FormClosed)
#Show the Form
return $form1.ShowDialog()
} #End Function
#Call the form
GUIBox | Out-Null

Powershell - get ad user information based on a dropdown.text value

I folks,
I've try my best to handle a LDAP query on a button click, but I can get the dropdown2.text to search a name instead I put the complet name like "smith, peter".
What I want is, if I put any of first name or Last name in the "Manager" field, the click button will searh and return me all the corresponding value in Active Directory event if it's a name or a family name. I'm not far, but I can't find where is my mistake
function GenerateForm {
set-Location c:\
add-PSSnapin quest.activeroles.admanagement
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
$form1 = New-Object System.Windows.Forms.Form
$searchldap = New-Object System.Windows.Forms.Button
$DropDownLabel = new-object System.Windows.Forms.Label
$DropDownLabel2 = new-object System.Windows.Forms.Label
$DropDown = new-object System.Windows.Forms.ComboBox
$DropDown2 = new-object System.Windows.Forms.ComboBox
#Handler
$handler_searchldap_click=
{
$manager = ""
$dropdown2.items.clear()
$manager = get-aduser -f {name -like $dropdown2.text}
foreach ($thing in $manager){
$useraccountname = $thing.name
$DropDown2.Items.Add($useraccountname) | Out-Null
}
}
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
#----------------------------------------------
#region Generated Form Code
$form1.Text = "User Creation software"
$form1.Name = "form1"
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 400
$System_Drawing_Size.Height = 200
$form1.ClientSize = $System_Drawing_Size
$DropDownArray = "Site1" , "Site2" , "Site3"
$DropDown2.Location = new-object System.Drawing.Size(125,80)
$DropDown2.Size = new-object System.Drawing.Size(150,27)
$dropdown2.DataBindings.DefaultDataSourceUpdateMode = 0
$dropdown2.TabIndex = 5
$dropdown2.Name = "dropdown2"
$DropDown2.add_TextUpdate({ Write-Host "TextUpdate. Updated text is: $($Dropdown2.Text)" })
$Form1.Controls.Add($DropDown2)
$DropDownLabel2 = new-object System.Windows.Forms.Label
$DropDownLabel2.Location = new-object System.Drawing.Size(50,80)
$DropDownLabel2.size = new-object System.Drawing.Size(50,27)
$DropDownLabel2.Text = "Manager:"
$Form1.Controls.Add($DropDownLabel2)
$DropDown.Location = new-object System.Drawing.Size(125,55)
$DropDown.Size = new-object System.Drawing.Size(150,27)
$dropdown.DataBindings.DefaultDataSourceUpdateMode = 0
$dropdown.TabIndex = 4
$dropdown.Name = "dropdown1"
$DropDownLabel = new-object System.Windows.Forms.Label
$DropDownLabel.Location = new-object System.Drawing.Size(50,58)
$DropDownLabel.size = new-object System.Drawing.Size(50,27)
$DropDownLabel.Text = "Location:"
$Form1.Controls.Add($DropDown)
$Form1.Controls.Add($DropDownLabel)
ForEach ($Item in $DropDownArray) {
$DropDown.Items.Add($Item) | Out-Null
}
###Button section
$searchldap.Location = New-Object System.Drawing.Size(275,80)
$searchldap.Size = New-Object System.Drawing.Size(100,20)
$searchldap.Text = "Search"
$searchldap.Add_Click($handler_searchldap_click)
$Form1.Controls.Add($searchldap)
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null
} #end of function
GenerateForm
Try this:
$filter = [scriptblock]::Create("Name -like '*$($dropdown2.text)*'")
$manager = get-aduser -f $filter
Powershell does not expand local variables used in filter script blocks before it passes them to the DC (via the AD Gateway Service). To get around that, create the filter script block from an expandable string