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
Related
I'm trying to copy the checked item in ListADGroup and copy to ListADGroup2. ListADGroup updates with all the groups but when I try adding them to ListADGroup2 it copies the right amount checkboxes but they are empty. Im not sure what is missing from the button command to copy the data properly.
Add-Type -AssemblyName "System.Windows.Forms"
Add-Type -AssemblyName "System.Drawing"
Add-Type -AssemblyName PresentationFramework
Clear-Host
#== Create a New Form ==#
$TSTAPP=New-Object System.Windows.Forms.Form
$TSTAPP.topmost=$true
$TSTAPP.Text="Test App"
$TSTAPP.Location.x=750
$TSTAPP.Location.Y=330
$TSTAPP.Size=New-Object System.Drawing.Size(750,330)
#== Now Lock the form so it cannot be re-sized ==#
$TSTAPP.MaximumSize=New-Object System.Drawing.Size(750,330)
$TSTAPP.MinimumSize=New-Object System.Drawing.Size(750,330)
#== Group List Label ==#
$GroupL = New-Object System.Windows.Forms.Label
$GroupL.Text = "Select Group:"
$GroupL.Location = New-Object System.Drawing.Point(4,5)
$GroupL.AutoSize = $true
$TSTAPP.Controls.Add($GroupL)
#== AD Users Listbox ==#
$ListADGroup = New-Object system.Windows.Forms.Listview
$ListADGroup.Width = 356
$ListADGroup.height = 220
$ListADGroup.location = New-Object System.Drawing.Point(4,22)
#$ListADGroup.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$ListADGroup.CheckBoxes = $true
$ListADGroup.Name = "Main"
$ListADGroup.AutoArrange = $true
$ListADGroup.GridLines = $true
$ListADGroup.MultiSelect = $false
$ListADGroup.View = "Details"
$ListADGroup.AutoSize = $true
#$ListADGroup.Columns[0].
$ListADGroup.Columns.Add("Groups")
$AllADGroups = Get-ADGroup -filter * -SearchBase 'OU=Accounts,DC=domain,DC=internal' -SearchScope subtree -Properties Name | Sort-Object Name | foreach{[void]$ListADGroup.Items.Add($_.name)}
$TSTAPP.controls.add($ListADGroup)
#== AD Users Listbox ==#
$ListADGroup2 = New-Object system.Windows.Forms.Listview
$ListADGroup2.Width = 356
$ListADGroup2.height = 220
$ListADGroup2.location = New-Object System.Drawing.Point(370,22)
#$ListADGroup2.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$ListADGroup2.CheckBoxes = $true
$ListADGroup2.Name = "Main"
$ListADGroup2.AutoArrange = $true
$ListADGroup2.GridLines = $true
$ListADGroup2.MultiSelect = $false
$ListADGroup2.View = "Details"
$ListADGroup2.AutoSize = $true
#$ListADGroup2.Columns.Width = 100
$ListADGroup2.Columns.Add("Groups2")
$TSTAPP.controls.add($ListADGroup2)
#== Add Button ==#
$AddGroup = New-Object system.Windows.Forms.Button
$AddGroup.text = "Add"
$AddGroup.width = 100
$AddGroup.height = 30
$AddGroup.location = New-Object System.Drawing.Point(265,249)
$AddGroup.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$TSTAPP.controls.add($AddGroup)
$AddGroup.Add_Click({
$itm = $ListADGroup.CheckedItems
foreach ($items in $itm){
$ListADGroup2.Items.Add($items.name)
}
})
$TSTAPP.ShowDialog()
If you try to debug using ISE or Visual Code you will see that the property containing the name is called Text
So replace :
$ListADGroup2.Items.Add($items.name)
by
$ListADGroup2.Items.Add($items.Text)
Good afternoon, dear forum users. Please help me with the next question. I am trying to create a GUI application in Powershell GUI. Since I am a beginner in programming and knowledge, I have not decided to contact the forum for help. The essence of the application is to search by full name in the Active Directory accounts of the required employee account and view the date the password was changed for this account.
I have a ready-made code that works when entering an account login in English. At the same time, I want to implement a search in Russian. The code that I give below searches in Russian, but only in text form displays a list of accounts by name, this text can only be copied. I ask you to tell me how you can program the program so that it searches not in the form of text, full name, but in the form of elements on whose name you can click with the mouse cursor and get the result. I attach a screenshot of the program https://i.stack.imgur.com/GJ5qP.png. Thank you in advance for your help.
$Form.Size = New-Object System.Drawing.Size(460,350) # Mold size
$Form.Text ="Pass info"
$Form.AutoSize = $false
$Form.MaximizeBox = $false # button expand program
$Form.MinimizeBox = $true # minimize program button
$Form.BackColor = "#c08888" # Form color
$Form.ShowIcon = $true # Enable icon (upper left corner) $ true, disable icon
$Form.SizeGripStyle = [System.Windows.Forms.SizeGripStyle]::Hide # Prevent form stretching
#$Form.SizeGripStyle = "Hide"
$Form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::Fixed3D # Prevent form stretching _2
$Form.WindowState = "Normal"
$Form.StartPosition = "CenterScreen" #loads the window in the center of the screen
$Form.Opacity = 1.0 # Form transparency
$Form.TopMost = $false #
Over other windows
########### Function start:
function Info {
$wks=$InputBox.text;
Write-Host $wks
$regex1 = "[^-a-zA-Z0-9_#.!#]+"
$regex2 = "[^-а-яА-Я0-9_#.!#]+"
If($wks -match $regex2) {
$Result1=Get-ADUser -identity $wks -Properties * | select CN -ExpandProperty CN
$outputBox.text=$Result1
$Result2=Get-ADUser -identity $wks -Properties * | select PasswordLastset -ExpandProperty PasswordLastset
$outputBox2.text=$Result2
}
If($wks -match $regex1) {
$wks2 = "$wks*"
Write-Host $wks2
$Result3=Get-AdUser -Filter 'name -Like $wks2' | Select Name -expandproperty Name| Sort Name | fl | out-string
Write-Host $Result3
#$Result3 = ($Result3 -replace ' ','_')
#$Result3 = $Result3 -split '_',2 -join ' '
$ListBox.text = $Result3
}
}
########### End Function.
############################################## Start text fields
#### Group selection of labels 2 and 3$groupBox = New-Object System.Windows.Forms.GroupBox
$groupBox.Location = New-Object System.Drawing.Size(10,230)
$groupBox.size = New-Object System.Drawing.Size(280,80)
$groupBox.text = "Info:"
$Form.Controls.Add($groupBox)
$FormLabel1 = New-Object System.Windows.Forms.Label
$FormLabel1.Text = "User AD:"
$FormLabel1.ForeColor = "#3009f1"
$FormLabel1.Font = "Microsoft Sans Serif,8"
$FormLabel1.Location = New-Object System.Drawing.Point(10,10)
$FormLabel1.AutoSize = $true
$Form.Controls.Add($FormLabel1)
$FormLabel2 = New-Object System.Windows.Forms.Label
$FormLabel2.Text = "ФИО:"
$FormLabel2.Location = New-Object System.Drawing.Point(10,25)
$FormLabel2.ForeColor = "#3009f1"
$FormLabel2.Font = "Microsoft Sans Serif,8"
$FormLabel2.AutoSize = $true
#$Form.Controls.Add($FormLabel2) # Метка явл. частью общ. Form
$groupBox.Controls.Add($FormLabel2) # Метка явл. частью groupBox
$FormLabel3 = New-Object System.Windows.Forms.Label
$FormLabel3.Text = "Дата:"
$FormLabel3.Location = New-Object System.Drawing.Point(10,47)
$FormLabel3.ForeColor = "#3009f1"
$FormLabel3.Font = "Microsoft Sans Serif,8"
$FormLabel3.AutoSize = $true
#$Form.Controls.Add($FormLabel3) # Метка явл. частью общ. Form
$groupBox.Controls.Add($FormLabel3) # Метка явл. частью groupBox
############################################ InputBox #########################################
$InputBox = New-Object System.Windows.Forms.TextBox
$InputBox.Location = New-Object System.Drawing.Size(65,5)
$InputBox.Size = New-Object System.Drawing.Size(150,20)
$Form.Controls.Add($InputBox)
$outputBox = New-Object System.Windows.Forms.TextBox
$outputBox.Location = New-Object System.Drawing.Size(80,20)
$outputBox.Size = New-Object System.Drawing.Size(180,20)
$outputBox.ReadOnly = $True
$groupBox.Controls.Add($outputBox)
$outputBox2 = New-Object System.Windows.Forms.TextBox
$outputBox2.Location = New-Object System.Drawing.Size(80,42)
$outputBox2.Size = New-Object System.Drawing.Size(180,42)
$outputBox2.ReadOnly = $True
$groupBox.Controls.Add($outputBox2)
############################################## ListBox
$ListBox = New-Object System.Windows.Forms.TextBox
$ListBox.Location = New-Object System.Drawing.Size(65,30)
$ListBox.Size = New-Object System.Drawing.Size(220,200)
$ListBox.MultiLine = $True #declaring the text box as multi-line
$ListBox.AcceptsReturn = $true
$ListBox.ScrollBars = "Vertical"
$ListBox.AcceptsTab = $true
$ListBox.WordWrap = $True
$ListBox.ReadOnly = $True
$Form.Controls.Add($ListBox)
############################################## End ListBox
############################################## search in Russian and in English
$regex1 = "[^-a-zA-Z0-9_#.!#]+"
$regex2 = "[^-а-яА-Я0-9_#.!#]+"
$TestName = "Mouse" # Mouse или мышь
If($TestName -match $regex1){echo "English '$TestName'"}
If($TestName -match $regex2){echo "Русский '$TestName'"}
get-aduser -filter 'name -like "*" ' | select name -expandproperty name
############################################## End search in Russian and in English
################ Button
$Button = New-Object System.Windows.Forms.Button
$Button.Location = New-Object System.Drawing.Size(310,20)
$Button.Size = New-Object System.Drawing.Size(110,80)
$Button.Text = "Загрузить данные"
$Button.BackColor = "#d7f705"
$Button.Add_Click({Info})
$Form.Controls.Add($Button)
################ End Button
################ Binding a button in the program to the Enter key on the keyboard ...
$Form.KeyPreview = $True
$Form.Add_KeyDown({if ($_.KeyCode -eq "Enter")
{
# if enter, perform click
$Button.PerformClick()
}
})
################ End Binding a button
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
This is some example how is works:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$MyForm = New-Object System.Windows.Forms.Form
$MyForm.Text = "USER info Lastlogondate"
$MyForm.Size = New-Object System.Drawing.Size(500, 500)
#user info
$allinfo=$null
#change your domin info
$allinfo=Get-ADUser -filter * -SearchBase "OU=users,DC=domain,DC=local" -properties Name, SamAccountName,Lastlogondate
#select in the column user name to fill $mTextBox1.Text
$Selectuser =
{
$c = $mDataGrid1.CurrentCell.columnindex
$colHeader = $mDataGrid1.columns[$c].name
if ($colHeader -eq "SamAccountName") {
$username = $mDataGrid1.CurrentCell.Value
$mTextBox1.Text = $username
Write-Host $username
}
} #
#usernema textbox--------------------------------------------
$mTextBox1 = New-Object System.Windows.Forms.TextBox
$mTextBox1.Text = ""
$mTextBox1.Top = "20"
$mTextBox1.Left = "26"
$mTextBox1.Anchor = "Left,Top"
$mTextBox1.Size = New-Object System.Drawing.Size(170, 23)
$MyForm.Controls.Add($mTextBox1)
#gridview
$mDataGrid1 = New-Object System.Windows.Forms.DataGridView
$mDataGrid1.Text = "DataGrid1"
$mDataGrid1.Top = "60"
$mDataGrid1.Left = "27"
$mDataGrid1.Anchor = "Left,Top"
$mDataGrid1.AutoSizeColumnsMode = 16
$mDataGrid1.add_CellContentDoubleClick($Selectuser)
$mDataGrid1.Size = New-Object System.Drawing.Size(400, 330)
$MyForm.Controls.Add($mDataGrid1)
#GetAllUsers button------------------------------------------
$mButton1 = New-Object System.Windows.Forms.Button
$mButton1.Text = "Get All Users"
$mButton1.Top = "20"
$mButton1.Left = "200"
$mButton1.Anchor = "Left,Top"
$mButton1.Size = New-Object System.Drawing.Size(100, 23)
$MyForm.Controls.Add($mButton1)
$mButton1.Add_Click( { GetAllusers})
Function GetAllusers {
$mDataGrid1.DataSource = $null
$array = New-Object System.Collections.ArrayList
$result=$allinfo |Select-Object Name, SamAccountName,Lastlogondate|sort -Property Name
$array.Addrange($result)
$mDataGrid1.Datasource = ($array)
$MyForm.Refresh()
}
#exit---------------------------------------------------------
$mButton4 = New-Object System.Windows.Forms.Button
$mButton4.Text = "Exit"
$mButton4.Top = "20"
$mButton4.Left = "320"
$mButton4.Anchor = "Left,Top"
$mButton4.Size = New-Object System.Drawing.Size(120, 23)
$mButton4.Add_Click( {$MyForm.Close()})
$MyForm.Controls.Add($mButton4)
$MyForm.ShowDialog()
I'm not entirely sure how to word this so bare with me. The orginization i work for is taking away a license for a software we use to connect to our network switches using a basic SSH connection. Just using PowerShell i know this command works for us. ssh username#IP_of_Switch now comes the fun part.
I want to make a GUI for our techs so they just have to select the switch name and not have to know every IP of all 100+ switches. I know for a drop down box it would look like this
$DropDownBox = New-Object System.Windows.Forms.ComboBox
$DropDownBox.Location = New-Object System.Drawing.Size(20,50)
$DropDownBox.Size = New-Object System.Drawing.Size(180,20)
$DropDownBox.DropDownHeight = 200
$Form.Controls.Add($DropDownBox)
$swList=#("1D","3D","3F","6E","Laundry","Chapel")
foreach ($sws in $swList) {$DropDownBox.Items.Add($sw)} #end foreach
What i want to do is have those Names be associated with their respective IP some how. AND HAVE A BUTTON TO CONNECT THEM TO SELECTED SWITCHI have a slight idea that i may need to have a txt file with the IP's. Any help would be greatly appreciated.
ComboBox is inherited from ListControl
You should provide Objects to ListItems. Each object should contain at least 2 properties: displayName and value ( you can change names of properties how you want ).
You need to set ComboBox's properties DisplayMember to name of property should be displayed.
Example:
In $FormEvent_Load scriptblock, we add items to ComboBox. Those items are objects with (at least) 2 properties - Name and Address. There we also set DisplayMember property of ComboBox to let it know, which property should be displayed in UI.
In $CBEvent_SelectedIndexChanged scriptblock, we get SelectedItem property from ComboiBox. SelectedItem contains original object we passed to ComboBox.Items.Add. There is Address field as you see, which can be used.
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
$form1 = New-Object System.Windows.Forms.Form
$combobox1 = New-Object System.Windows.Forms.ComboBox
$label1 = New-Object System.Windows.Forms.Label
$FormEvent_Load = {
$combobox1.DisplayMember = 'Name'
$combobox1.Items.Add(
[PSCustomObject]#{
'Name' = 'Switch1'
'Address' = [ipaddress]::Parse('1.1.1.1')
})
$combobox1.Items.Add(
[PSCustomObject]#{
'Name' = 'Switch2'
'Address' = [ipaddress]::Parse('2.12.21.22')
})
}
$CBEvent_SelectedIndexChanged = {
$label1.Text = $combobox1.SelectedItem.Address.ToString()
}
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 292
$System_Drawing_Size.Height = 266
$form1.ClientSize = $System_Drawing_Size
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 83
$System_Drawing_Point.Y = 199
$label1.Location = $System_Drawing_Point
$label1.Text = 'Select IP'
$form1.Controls.Add($label1)
$form1.Controls.Add($combobox1)
$form1.add_Load($FormEvent_Load)
$ComboBox1.add_SelectedIndexChanged($CBEvent_SelectedIndexChanged)
$form1.ShowDialog()| Out-Null
This is just an example but it does work. I used a simple csv file to hold the switch IP Addresses. I edited an answer for the majority of this script so I will give credit for that Powershell default dropdown value
CSV File
1D,127.0.0.1
3D,127.0.0.2
3F,127.0.0.3
6E,127.0.0.4
Laundry,127.0.0.5
Chapel,127.0.0.6
Script
########################
# Edit This item to change the DropDown Values
$switchesFilePath = "C:\temp\switches.csv"
$switches = ConvertFrom-Csv (Get-Content -Path $switchesFilePath)
# This Function Returns the Selected Value and Closes the Form
function Return-DropDown {
$script:Choice = $DropDown.SelectedItem
Write-Host "The selected switch is $($script:Choice.Name) and it's IP is $($script:Choice.IPAddress)"
Write-Host "The ssh command would be ---- ssh username#$($script:Choice.IPAddress)"
$Form.Close()
}
function selectSwitch{
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form = New-Object System.Windows.Forms.Form
$Form.width = 300
$Form.height = 150
$Form.Text = ”DropDown”
$DropDown = new-object System.Windows.Forms.ComboBox
$DropDown.Location = new-object System.Drawing.Size(100,10)
$DropDown.Size = new-object System.Drawing.Size(130,30)
$DropDown.SelectedItem = $DropDown.Items[0]
$DropDown.DisplayMember = 'Name'
[void] $DropDown.Items.AddRange($switches)
$Form.Controls.Add($DropDown)
$DropDownLabel = new-object System.Windows.Forms.Label
$DropDownLabel.Location = new-object System.Drawing.Size(10,10)
$DropDownLabel.size = new-object System.Drawing.Size(100,40)
$DropDownLabel.Text = "Select a network switch"
$Form.Controls.Add($DropDownLabel)
$Button = new-object System.Windows.Forms.Button
$Button.Location = new-object System.Drawing.Size(100,50)
$Button.Size = new-object System.Drawing.Size(100,20)
$Button.Text = "Connect to a switch"
$Button.Add_Click({Return-DropDown})
$form.Controls.Add($Button)
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
return $script:choice
}
$switch = selectSwitch
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
I'm trying to create a powershell form that will get all processes into a datagridview (which works OK so far). I'm then adding an additional column infront of the datasource with each row as a checkbox.
I'd then like to press a button on my form which starts the Function called Do-Grid, and it is meant to go through and see which checkboxes in this first column have been checked.
And this is where I get stuck. I'm unable to figure out how to loop through each row/cell only in this column and see which checkbox has been ticked (or have the value of true).
Thank you.
Function GenerateForm {
[Void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$ButtonUpdateGrid = New-Object Windows.Forms.Button
$ButtonUpdateGrid.Location = New-Object Drawing.Point 7,15
$ButtonUpdateGrid.size = New-Object Drawing.Point 90,23
$ButtonUpdateGrid.Text = "&Get Packages"
$ButtonUpdateGrid.add_click({Get-info})
$Button1 = New-Object Windows.Forms.Button
$Button1.Location = New-Object Drawing.Point 200,15
$Button1.size = New-Object Drawing.Point 90,23
$Button1.Text = "columns"
$button1.add_Click($button1_OnClick)
$ButtonStartExport = New-Object Windows.Forms.Button
$ButtonStartExport.Location = New-Object Drawing.Point 100,15
$ButtonStartExport.size = New-Object Drawing.Point 90,23
$ButtonStartExport.Text = "rows"
$ButtonStartExport.add_click({Do-Grid})
$dataGridView1 = New-Object System.Windows.Forms.DataGridView
$dataGridView1.Location = New-Object Drawing.Point 7,40
$dataGridView1.size = New-Object Drawing.Point 1000,700
$dataGridView1.MultiSelect = $false
$dataGridView1.ColumnHeadersVisible = $true
$dataGridView1.RowHeadersVisible = $false
$form = New-Object Windows.Forms.Form
$form.text = "Package Exporter v0.1"
$form.Size = New-Object Drawing.Point 1024, 768
$form.topmost = 1
$form.Icon = [system.drawing.icon]::ExtractAssociatedIcon($PSHOME + "\powershell.exe")
$form.Controls.Add($dataGridView1)
$form.controls.add($Button1)
$form.controls.add($ButtonStartExport)
$form.controls.add($ButtonUpdateGrid)
#$form.add_Load($OnLoadForm)
$form.ShowDialog()
}
Function Get-info{
If($datagridview1.columncount -gt 0){
$dataGridview1.DataSource = $null
$DataGridView1.Columns.RemoveAt(0)
}
$Column1 = New-Object System.Windows.Forms.DataGridViewCheckBoxColumn
$Column1.width = 30
$Column1.name = "Exp"
$DataGridView1.Columns.Add($Column1)
$array = New-Object System.Collections.ArrayList
$Script:procInfo = get-process | Select-Object name, company, description, product, id, vm, fileversion
$array.AddRange($procInfo)
$dataGridview1.DataSource = $array
$form.refresh()
}
Function Do-Grid{
#?????????????????????????????????? not really sure what to do here
for($i=0;$i -le $datagridview1.Rows.Count;$i++){
write-host $datagridview1.Rows[$i].value
}
}
Generate Form
Function Do-Grid{
for($i=0;$i -lt $datagridview1.RowCount;$i++){
if($datagridview1.Rows[$i].Cells['exp'].Value -eq $true)
{
write-host "cell #$i is checked"
#uncheck it
#$datagridview1.Rows[$i].Cells['exp'].Value=$false
}
else
{
#check it
#$datagridview1.Rows[$i].Cells['exp'].Value=$true
write-host "cell #$i is not-checked"
}
}
}