Powershell InputBox (selfmade) only returns "Cancel" - powershell

`In a Powershell project - small GUI with Winforms - I need a passwordbox. I wrote a test-function but cannot manage to get the correct output ... I only get "Cancel"
I get the same result if I do not use
$inpBox.PasswordChar = "*"
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[System.Windows.Forms.Application]::EnableVisualStyles()
function InputForm {
param($loggedInUser="Spock")
$inpForm = New-Object System.Windows.Forms.Form
$inpForm.Height = 120
$inpForm.Width = 350
# $inpForm.Icon = "$PSScriptRoot\Heidelberg-H.ico"
$inpForm.Text = "Authentication Window"
$inpForm.MaximizeBox = $false
$inpForm.MinimizeBox = $false
$inpForm.FormBorderStyle = "FixedDialog"
$inpForm.StartPosition = "CenterScreen" # moves to center of screen
$inpForm.Topmost = $true # Make it Topmost
# create a Label
$inpLbl = New-Object System.Windows.Forms.Label
$inpLbl.Width = 300
$inpLbl.Location = New-Object System.Drawing.Point(10,10)
$inpLbl.Text = "Please type in the password for user: " + $loggedInUser
# create a InputBox for the password
$inpBox = New-Object System.Windows.Forms.TextBox
$inpBox.Width = 200
$inpBox.Height = 25
$inpBox.PasswordChar = "*"
$inpBox.Text = "********"
$inpBox.Location = New-Object System.Drawing.Point(10, 35)
# create an OK Button
$inpBtn = New-Object System.Windows.Forms.Button
$inpBtn.Width = 60
$inpBtn.Height = 25
$inpBtn.Text = "OK"
$inpBtn.Location = New-Object System.Drawing.Point(250,33)
$form.AcceptButton = $inpBtn
$inpForm.Controls.AddRange(#($inpLbl, $inpBox, $inpBtn))
# OK-Button - Click event
$inpBtn.Add_Click({
$inpForm.Close()
return $inpBox.Text
})
$inpForm.ShowDialog()
}
# MAIN
$PW = InputForm (Get-WMIObject -ClassName Win32_ComputerSystem).Username
write-host $PW

The problem is with this last part of your function:
$inpBtn.Add_Click({
$inpForm.Close()
return $inpBox.Text
})
$inpForm.ShowDialog()
Instead of registering a custom handler for the Click event, you'll want to assign a value to the DialogResult property on the button - then inspect that result and return the value of the textbox from the function:
$inpBtn.DialogResult = 'OK'
if($inpForm.ShowDialog() -eq 'OK'){
return $inpBox.Text
}
else {
throw "User canceled password prompt!"
}

Related

Cannot call show dialog() on a null-valued expression

I am trying to open the next page of my Winforms script and atm on first launch the error is get when clicking the next button is "you cannot call a method on a null-valued expression" [void] $Form_UserInformation.ShowDialog() being the issue code here. When I run it the second time it runs fine but this doesn't work for an EXE file as it closes it and doesn't remember the previous session.
# HomePage Form
$Form_HomePage = New-Object System.Windows.Forms.Form
$Form_HomePage.text = "New User Script"
$Form_HomePage.Size = New-Object System.Drawing.Size(400,400)
$Form_HomePage.FormBorderStyle = "FixedDialog"
$Form_HomePage.TopMost = $false
$Form_HomePage.MaximizeBox = $false
$Form_HomePage.MinimizeBox = $true
$Form_HomePage.ControlBox = "true"
$Form_HomePage.StartPosition = "CenterScreen"
$Form_HomePage.Font = "Segoe UI"
# Title label
$label_HomeTitle = New-Object System.Windows.Forms.Label
$label_HomeTitle.Location = New-Object System.Drawing.Size(47,8)
$label_HomeTitle.Size = New-Object System.Drawing.Size(300,42)
$label_HomeTitle.Font = New-Object System.Drawing.Font("Segoe UI",24,[System.Drawing.FontStyle]::Regular)
$label_HomeTitle.TextAlign = "MiddleCenter"
$label_HomeTitle.Text = "Kuehne && Nagel"
$Form_HomePage.Controls.Add($label_HomeTitle)
# Subheading label
$label_HomeSubTitle = New-Object System.Windows.Forms.Label
$label_HomeSubTitle.Location = New-Object System.Drawing.Size(50,60)
$label_HomeSubTitle.Size = New-Object System.Drawing.Size(300,42)
$label_HomeSubTitle.Font = New-Object System.Drawing.Font("Segoe UI",16,[System.Drawing.FontStyle]::Regular)
$label_HomeSubTitle.TextAlign = "MiddleCenter"
$label_HomeSubTitle.Text = "New User Script"
$Form_HomePage.Controls.Add($label_HomeSubTitle)
# Next button
$button_HomeStart = New-Object System.Windows.Forms.Button
$button_HomeStart.Location = New-Object System.Drawing.Size(75,200)
$button_HomeStart.Size = New-Object System.Drawing.Size(240,32)
$button_HomeStart.TextAlign = "MiddleCenter"
$button_HomeStart.Text = "Start"
$button_HomeStart.Add_Click({
[void] $Form_UserInformation.ShowDialog()
$Form_HomePage.Hide()
})
$Form_HomePage.Controls.Add($button_HomeStart)
# About button
$button_About = New-Object System.Windows.Forms.Button
$button_About.Location = New-Object System.Drawing.Size(75,250)
$button_About.Size = New-Object System.Drawing.Size(240,32)
$button_About.TextAlign = "MiddleCenter"
$button_About.Text = "About"
$button_About.Add_Click({
})
$Form_HomePage.Controls.Add($button_About)
# Exit button
$button_HomeExit = New-Object System.Windows.Forms.Button
$button_HomeExit.Location = New-Object System.Drawing.Size(75,300)
$button_HomeExit.Size = New-Object System.Drawing.Size(240,32)
$button_HomeExit.TextAlign = "MiddleCenter"
$button_HomeExit.Text = "Exit"
$button_HomeExit.Add_Click({
$Form_HomePage.Close()
})
$Form_HomePage.Controls.Add($button_HomeExit)
# Show Form
$Form_HomePage.Add_Shown({$Form_HomePage.Activate()})
[void] $Form_HomePage.ShowDialog()
# User Information Form
$Form_UserInformation = New-Object System.Windows.Forms.Form
$Form_UserInformation.text = "New User Script"
$Form_UserInformation.Size = New-Object System.Drawing.Size(400,400)
$Form_UserInformation.FormBorderStyle = "FixedDialog"
$Form_UserInformation.TopMost = $false
$Form_UserInformation.MaximizeBox = $false
$Form_UserInformation.MinimizeBox = $true
$Form_UserInformation.ControlBox = "true"
$Form_UserInformation.StartPosition = "CenterScreen"
$Form_UserInformation.Font = "Segoe UI"

Powershell GUI. Selecting an item from a dynamic ListBox with subsequent unloading of user information from Active Directory Ask a question

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

Variable is an empty string even after writing the string to host

I'm trying to build a little app to help admins swap powerapps ownership around in PowerShell. I'm sure this is me misunderstanding how scopes work in PowerShell but I'm stumped and need a little help.
The app is pretty simple, it queries the PowerApp environment for a list of apps, their owners, and their GUIDs and presents them in a datagridview. Users select the app they're going to change, click a button, put an email address in, and then click another button. On that click, the app grabs the user's GUID from AAD and then runs a command to flip ownership of the app to that user's GUID.
But for some reason, the second function keeps reporting that the GUID and App Name I collected in the first screen are empty strings.
Here's the whole thing (minus credential info, natch):
#Get Apps on environment
$apps = Get-AdminPowerApp -EnvironmentName $powerAppEnv
#Form Details
$ChangePowerAppOwnership = New-Object system.Windows.Forms.Form
$ChangePowerAppOwnership.ClientSize = New-Object System.Drawing.Point(500,300)
$ChangePowerAppOwnership.text = "Change PowerApp Ownership"
$ChangePowerAppOwnership.TopMost = $false
$appsLabel = New-Object system.Windows.Forms.Label
$appsLabel.text = "Available Apps"
$appsLabel.AutoSize = $true
$appsLabel.width = 25
$appsLabel.height = 10
$appsLabel.location = New-Object System.Drawing.Point(15,20)
$appsLabel.Font = New-Object System.Drawing.Font('Segoe UI',10)
$availableApps = New-Object system.Windows.Forms.DataGridView
$availableApps.width = 470
$availableApps.height = 200
$availableApps.location = New-Object System.Drawing.Point(15,40)
$availableApps.MultiSelect = $false
$availableApps.SelectionMode = "FullRowSelect"
$availableApps.ColumnCount = 3
$availableApps.ColumnHeadersVisible = $true
$availableApps.Columns[0].Name = "App Name"
$availableApps.Columns[1].Name = "Current Owner"
$availableApps.Columns[2].Name = "GUID"
foreach($app in $apps){
$availableApps.Rows.Add(#($app.DisplayName,($app.Owner | Select-Object -Expand displayName),$app.AppName))
}
$promptForAdmin = New-Object system.Windows.Forms.Button
$promptForAdmin.text = "Next"
$promptForAdmin.width = 60
$promptForAdmin.height = 30
$promptForAdmin.location = New-Object System.Drawing.Point(424,260)
$promptForAdmin.Font = New-Object System.Drawing.Font('Segoe UI',10)
$promptForAdmin.Add_Click({ GetNewAdmin $availableApps.SelectedRows})
$adminLabel = New-Object system.Windows.Forms.Label
$adminLabel.text = "New Administrator"
$adminLabel.AutoSize = $true
$adminLabel.width = 25
$adminLabel.height = 10
$adminLabel.location = New-Object System.Drawing.Point(14,13)
$adminLabel.Font = New-Object System.Drawing.Font('Segoe UI',10)
$adminEmailField = New-Object system.Windows.Forms.TextBox
$adminEmailField.multiline = $false
$adminEmailField.width = 200
$adminEmailField.height = 20
$adminEmailField.location = New-Object System.Drawing.Point(135,12)
$adminEmailField.Font = New-Object System.Drawing.Font('Segoe UI',10)
$changeAppAdmin = New-Object system.Windows.Forms.Button
$changeAppAdmin.text = "Go"
$changeAppAdmin.width = 60
$changeAppAdmin.height = 30
$changeAppAdmin.location = New-Object System.Drawing.Point(424,260)
$changeAppAdmin.Font = New-Object System.Drawing.Font('Segoe UI',10)
$ChangePowerAppOwnership.controls.AddRange(#($appsLabel,$availableApps,$promptForAdmin))
$ChangePowerAppOwnership.ShowDialog()
function GetNewAdmin {
param($selectedRows)
$selectedAppGuid = $selectedRows | ForEach-Object{ $_.Cells[2].Value }
$selectedAppName = $selectedRows | ForEach-Object{ $_.Cells[0].Value }
Write-Host "Selected App GUID: $selectedAppGuid" #this and the following command show values
Write-Host "Selected App Name: $selectedAppName"
$appsLabel.Visible = $false
$availableApps.Visible = $false
$promptForAdmin.Visible = $false
$changeAppAdmin.Add_Click( { AssignNewAdmin $selectedAppGuid $selectedAppName $adminEmailField.Text} )
$ChangePowerAppOwnership.controls.AddRange(#($adminLabel,$adminEmailField,$changeAppAdmin))
}
function AssignNewAdmin {
param(
$selectedAppGuid,
$selectedAppName,
$newAdminEmail
)
Write-Host "AppID: $selectedAppGuid" #this is always empty
Connect-AzureAD -Credential $credentials
$user = Get-AzureADUser -ObjectId $newAdminEmail
$newAppOwnerGuid = $user | select ObjectId
$newAppOwnerName = $user | select DisplayName
$msgBoxMessage = "Are you sure you want to grant ownership of $selectedAppName to $newAppOwnerName`?"
$msgBoxInput = [System.Windows.Forms.MessageBox]::Show($msgBoxMessage,"Confirm","YesNo","Error")
switch ($msgBoxInput){
'Yes'{
Set-AdminPowerAppOwner -AppName $selectedAppGuid -EnvironmentName $powerAppEnv -AppOwner $newAppOwnerGuid
# try{
# $ChangePowerAppOwnership.Close()
# }
# catch{
# Write-Host "Could not update this app's administrator role."
# }
}
'No' {
$ChangePowerAppOwnership.Close()
}
}
}
Move the functions to the top or at least higher than $ChangePowerAppOwnership.ShowDialog() or the script wont find them(the execution stops till you close the Form...).
The same goes for the function AssignNewAdmin as it is used in GetNewAdmin but defined later.
Courtesy of Jeroen Mostert's comment, adding GetNewClosure to my second Add_Click function did the trick.

Prevent Powershell GUI from closing

I want to prevent my Powershell Form from closing after a submit button is pressed. After the function "search_PC" there is no more code and the form closes. I want to still be able to write stuff in there after the function is finished. I have already tried the pause function and while($true) loops. I would be very happy about an answer.
Import-Module ActiveDirectory
# Assembly for GUI
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
# Create Form
$objForm = New-Object System.Windows.Forms.Form
$objForm.Size = New-Object System.Drawing.Size(400,500)
$objForm.Backcolor="white"
$objForm.StartPosition = "CenterScreen"
$objForm.Text = "Example Software"
$objForm.Icon="C:\Users\...\icon.ico"
# Label
$objLabel1 = New-Object System.Windows.Forms.Label
$objLabel1.Location = New-Object System.Drawing.Size(80,30)
$objLabel1.Size = New-Object System.Drawing.Size(60,20)
$objLabel1.Text = "UserID:"
$objForm.Controls.Add($objLabel1)
# Textbox
$objTextBox1 = New-Object System.Windows.Forms.TextBox
$objTextBox1.Location = New-Object System.Drawing.Size(160,28)
$objTextBox1.Size = New-Object System.Drawing.Size(100,20)
$objForm.Controls.Add($objTextBox1)
# Label
$objLabel2 = New-Object System.Windows.Forms.Label
$objLabel2.Location = New-Object System.Drawing.Size(80,72)
$objLabel2.Size = New-Object System.Drawing.Size(80,20)
$objLabel2.Text = "PC-Name:"
$objForm.Controls.Add($objLabel2)
# Textbox
$objTextBox2 = New-Object System.Windows.Forms.TextBox
$objTextBox2.Location = New-Object System.Drawing.Size(160,70)
$objTextBox2.Size = New-Object System.Drawing.Size(100,20)
$objForm.Controls.Add($objTextBox2)
# Button for closing
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(100,220)
$CancelButton.Size = New-Object System.Drawing.Size(163,25)
$CancelButton.Text = "Exit"
$CancelButton.Name = "Exit"
$CancelButton.DialogResult = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)
# Checkbox
$objTypeCheckbox1 = New-Object System.Windows.Forms.Checkbox
$objTypeCheckbox1.Location = New-Object System.Drawing.Size(80,120)
$objTypeCheckbox1.Size = New-Object System.Drawing.Size(500,20)
$objTypeCheckbox1.Text = "Internal Session Support"
$objTypeCheckbox1.TabIndex = 1
$objTypeCheckbox1.Add_Click({$objTypeCheckbox2.Checked = $false})
$objForm.Controls.Add($objTypeCheckbox1)
# Checkbox
$objTypeCheckbox2 = New-Object System.Windows.Forms.Checkbox
$objTypeCheckbox2.Location = New-Object System.Drawing.Size(80,140)
$objTypeCheckbox2.Size = New-Object System.Drawing.Size(500,20)
$objTypeCheckbox2.Text = "Session Support Internal & external"
$objTypeCheckbox2.TabIndex = 2
$objTypeCheckbox2.Add_Click({$objTypeCheckbox1.Checked = $false})
$objForm.Controls.Add($objTypeCheckbox2)
# Button fo checking the User Input
$SubmitButton = New-Object System.Windows.Forms.Button
$SubmitButton.Location = New-Object System.Drawing.Size(100,190)
$SubmitButton.Size = New-Object System.Drawing.Size(163,25)
$SubmitButton.Text = "Submit"
$SubmitButton.Name = "Submit"
$SubmitButton.DialogResult = "OK"
$objForm.AcceptButton = $SubmitButton
$SubmitButton.Add_Click({
$User = $objTextBox1.Text
$PC = $objTextBox2.Text
# Check if all User Inputs are filled out
if ( !($User.trim()) -or !($PC.trim()) ) {
[void] [Windows.Forms.MessageBox]::Show("Please fill out every value!", "Error", [Windows.Forms.MessageBoxButtons]::ok, [Windows.Forms.MessageBoxIcon]::Warning)}
if($objTypeCheckbox1.checked -eq $true) {$Software = "Internal"}
elseif($objTypeCheckbox2.checked -eq $true) {$Software = "Internal&External"}
else {[void] [Windows.Forms.MessageBox]::Show("Please fill out every value!", "Error", [Windows.Forms.MessageBoxButtons]::ok, [Windows.Forms.MessageBoxIcon]::Warning)}
search_user
})
$objForm.Controls.Add($SubmitButton)
$statusBar1 = New-Object System.Windows.Forms.StatusBar
$objForm.controls.add($statusBar1)
function createFile
{
$Date = Get-Date -Format d.M.yyyy
$Time = (Get-Date).ToString(„HH:mm:ss“)
$Time2 = (Get-Date).ToString(„HH-mm-ss“)
$Date2 = Get-Date -Format yyyy-M-d;
$FileName = $Time2 + " " + $Date2
$wrapper = New-Object PSObject -Property #{ 1 = $Date; 2 = $Time; 3 = $User; 4 = $PC; 5 = $Software }
Export-Csv -InputObject $wrapper -Path C:\Users\...\$FileName.csv -NoTypeInformation
[void] [Windows.Forms.MessageBox]::Show("Successful!")
}
function search_user
{
if (#(Get-ADUser -Filter {SamAccountName -eq $User}).Count -eq 0) {
$objTextBox1.BackColor = "Red";
$statusBar1.Text = "Couldn't find user!"
$objForm.Dispose()
}
else{$objTextBox1.BackColor = "Green"
search_PC}
}
function search_PC
{
$Client = $PC
if (#(Get-ADComputer -Filter {DNSHostName -eq $Client}).Count -eq 0) {
$objTextBox2.BackColor = "Red";
$statusBar1.Text = "Couldn't find PC!"
$objForm.Dispose()
}
else{$objTextBox2.BackColor = "Green"
createFile}
}
$objForm.ShowDialog() #Showing Form and elements
Screenshot of the form:
This line is your problem:
$SubmitButton.DialogResult = "OK"
It should be:
$SubmitButton.DialogResult = [System.Windows.Forms.DialogResult]::None
Or just be removed.
DialogResult

Can't get ComboBox text to appear correctly [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a script that will do the following:
Create a Form with 2 ComboBoxes and a Text Box for user entry
I populate ComboBox 1 and populate ComboBox 2 based on the selection from ComboBox 1. Another thing that partially works is I can get Text to appear on the form based on the selection of ComboBox 1.
My Challenges are challenges I have, by priority are:
Challenge 1:
How can I change the the text on the form doesn't update if I change the selection in ComboBox 1. selection in ComboBox 1?
Challenge 2: (linked to Challenge 1)
I am looking for a way to combing ComboBox 1 with ComboBox 2 with the Text Box
Example: Comp1-Tst-MyTst?
Challenge 3:
I'm looking to import a CSV file / OR using a Get-AD.... for the variables instead of hard coding in the script.
Challenge 4:
I'm struggling with adding an Icon to the form
Challenge 5:
I'd like to prevent the Ok Button from appearing until a Checkbox is checked
Here's the code I have:
# Below is one of the Array's I'm adding
$ADSites=#("S01","S02","S03")
$ADSiteS01=#("AAA","BBB","CCC")
$ADSiteS02=#("DDD","EEE","FFF")
$ADSiteS03=#("GGG","HHH","JJJ")
####################################################################################################
##### Create Combo Boxes
####################################################################################################
$Form = New-Object System.Windows.Forms.Form
$Form.Size = New-Object System.Drawing.Size(625,625)
$Form.FormBorderStyle = "FixedToolWindow"
$Combobox1 = New-Object System.Windows.Forms.Combobox
$Combobox1.Location = New-Object System.Drawing.Size(26,25)
$Combobox1.Size = New-Object System.Drawing.Size(105,20)
$Combobox1.items.AddRange($ADSites)
$combobox2 = New-Object System.Windows.Forms.Combobox
$combobox2.Location = New-Object System.Drawing.Size(143,25)
$combobox2.Size = New-Object System.Drawing.Size(105,20)
$textBoxFPS = New-Object System.Windows.Forms.TextBox
$textBoxFPS.Location = New-Object System.Drawing.Point(26,75)
$textBoxFPS.Size = New-Object System.Drawing.Size(165,20)
$form.Controls.Add($textBoxFPS)
$Form.Controls.Add($combobox1)
$Form.Controls.Add($combobox2)
################################################################################################
##### Create Text Box
################################################################################################
$textBoxFPS = New-Object System.Windows.Forms.TextBox
$textBoxFPS.Location = New-Object System.Drawing.Point(26,75)
$textBoxFPS.Size = New-Object System.Drawing.Size(165,20)
$form.Controls.Add($textBoxFPS)
################################################################################################
##### Add Labels for the Combo Boxes
###################################################################################################
$lbADSub = New-Object System.Windows.Forms.Label
$lbADSub.Text = "Select AD Site"; $lbADSub.Top = 5; $lbADSub.Left = 26; $lbADSub.Autosize = $true
$form.Controls.Add($lbADSub)
$lbDeptSub = New-Object System.Windows.Forms.Label
$lbDeptSub.Text = "Select Department"; $lbDeptSub.Top = 5; $lbDeptSub.Left = 143;
$lbDeptSub.Autosize = $true
$form.Controls.Add($lbDeptSub)
$lbFPSSub = New-Object System.Windows.Forms.Label
$lbFPSSub.Text = "Type in the Asset Tag"; $lbFPSSub.Top = 55; $lbFPSSub.Left = 26;
$lbFPSSub.Autosize = $true
$form.Controls.Add($lbFPSSub)
## CheckBox
$chkThis = New-Object Windows.Forms.checkbox
$chkThis.Text = "Verify New Computer Name" ; $chkThis.Left = 26; $chkThis.Top = 105;
$chkThis.AutoSize = $true
$chkThis.Checked = $false # set a default value
$form.Controls.Add($chkThis)
<#
$lbCompSub = New-Object System.Windows.Forms.Label
$lbCompSub.Text = "Verify Computer Name"; $lbCompSub.Top = 105; $lbCompSub.Left = 26;
$lbCompSub.Autosize = $true
$form.Controls.Add($lbCompSub)
#>
############################################################################################
##### Create Ok and Cancel Buttons
############################################################################################
$buttonPanel = New-Object Windows.Forms.Panel
$buttonPanel.Size = New-Object Drawing.Size #(400,40)
$buttonPanel.Dock = "Bottom"
## Creating the Ok Button
$okButton = New-Object Windows.Forms.Button
$okButton.Top = $cancelButton.Top ; $okButton.Left = $cancelButton.Left - $okButton.Width - 5
$okButton.Text = "Ok"
$okButton.DialogResult = "Ok"
$okButton.Anchor = "Left"
## Creating the Cancel Button
$cancelButton = New-Object Windows.Forms.Button
$cancelButton.Left = $buttonPanel.Height - $cancelButton.Height - 10; $cancelButton.Left = $buttonPanel.Width - $cancelButton.Width - 10
$cancelButton.Text = "Cancel"
$cancelButton.DialogResult = "Cancel"
$cancelButton.Anchor = "Right"
## Add the buttons to the button panel
$buttonPanel.Controls.Add($okButton)
$buttonPanel.Controls.Add($cancelButton)
## Add the button panel to the form
$form.Controls.Add($buttonPanel)
## Set Default actions for the buttons
$form.AcceptButton = $okButton # ENTER = Ok
$form.CancelButton = $cancelButton # ESCAPE = Cancel
##################################################################################################
##### Now we do stuff
##################################################################################################
# Populate Combobox 2 When Combobox 1 changes
$ComboBox1_SelectedIndexChanged= {
$combobox2.Items.Clear() # Clear the list
$combobox2.Text = $null # Clear the current entry
Switch ($ComboBox1.Text) {
"S01"{
$ADSiteS01 | ForEach {
$labelClub = New-Object System.Windows.Forms.Label
$labelClub.Location = New-Object System.Drawing.Point(20,200)
$labelClub.Size = New-Object System.Drawing.Size(280,20)
$labelClub.Text = "$($combobox1.SelectedItem)-"
$form.Controls.Add($labelClub)
$combobox2.Items.Add($_)
#$labelClub.Text = "$($combobox2.SelectedItem)-"
}
}
"S02"{
$ADSiteS02 | ForEach {
$labelClub = New-Object System.Windows.Forms.Label
$labelClub.Location = New-Object System.Drawing.Point(20,200)
$labelClub.Size = New-Object System.Drawing.Size(280,20)
$labelClub.Text = "$($combobox1.SelectedItem)-"
$form.Controls.Add($labelClub)
$combobox2.Items.Add($_)
}
}
"S03"{
$ADSiteS03 | ForEach {
$labelClub = New-Object System.Windows.Forms.Label
$labelClub.Location = New-Object System.Drawing.Point(20,200)
$labelClub.Size = New-Object System.Drawing.Size(280,20)
$labelClub.Text = "$($combobox1.SelectedItem)-"
$form.Controls.Add($labelClub)
$combobox2.Items.Add($_)
}
}
}
}
$ComboBox1.add_SelectedIndexChanged($ComboBox1_SelectedIndexChanged)
$Form.ShowDialog()
This should help you out on the combo box issue and the OK button:
# Below is one of the Array's I'm adding
$ADSites=#("S01","S02","S03")
$ADSiteS01=#("AAA","BBB","CCC")
$ADSiteS02=#("DDD","EEE","FFF")
$ADSiteS03=#("GGG","HHH","JJJ")
Add-Type -AssemblyName System.Windows.Forms
#
####################################################################################################
##### Create Combo Boxes
####################################################################################################
$Form = New-Object System.Windows.Forms.Form
$Form.Size = '625,625'
$Form.FormBorderStyle = "FixedToolWindow"
#
$Combobox1 = New-Object System.Windows.Forms.Combobox
$Combobox1.Location = '26,25'
$Combobox1.Size = '105,20'
$Combobox1.items.AddRange($ADSites)
#
$combobox2 = New-Object System.Windows.Forms.Combobox
$combobox2.Location = '143,25'
$combobox2.Size = '105,20'
#
#
$Form.Controls.Add($combobox1)
$Form.Controls.Add($combobox2)
################################################################################################
##### Create Text Box
################################################################################################
$textBoxFPS = New-Object System.Windows.Forms.TextBox
$textBoxFPS.Location = '26,75'
$textBoxFPS.Size = '165,20'
$textBoxFPS.Text = 'xx'
$form.Controls.Add($textBoxFPS)
################################################################################################
##### Add Labels for the Combo Boxes
###################################################################################################
$lbADSub = New-Object System.Windows.Forms.Label
$lbADSub.Text = "Select AD Site"; $lbADSub.Top = 5; $lbADSub.Left = 26; $lbADSub.Autosize = $true
$form.Controls.Add($lbADSub)
$lbDeptSub = New-Object System.Windows.Forms.Label
$lbDeptSub.Text = "Select Department"; $lbDeptSub.Top = 5; $lbDeptSub.Left = 143;
$lbDeptSub.Autosize = $true
$form.Controls.Add($lbDeptSub)
$lbFPSSub = New-Object System.Windows.Forms.Label
$lbFPSSub.Text = "Type in the Asset Tag"; $lbFPSSub.Top = 55; $lbFPSSub.Left = 26;
$lbFPSSub.Autosize = $true
$form.Controls.Add($lbFPSSub)
## CheckBox
$chkThis = New-Object Windows.Forms.checkbox
$chkThis.Text = "Verify New Computer Name" ; $chkThis.Left = 26; $chkThis.Top = 105;
$chkThis.AutoSize = $true
$chkThis.Checked = $false # set a default value
$form.Controls.Add($chkThis)
############################
# Label for choice selection
############################
$labelClub = New-Object System.Windows.Forms.Label
$labelClub.Location = '20,200'
$labelClub.Size = '280,20'
$labelClub.Text = "-"
$form.Controls.Add($labelClub)
<#
$lbCompSub = New-Object System.Windows.Forms.Label
$lbCompSub.Text = "Verify Computer Name"; $lbCompSub.Top = 105; $lbCompSub.Left = 26;
$lbCompSub.Autosize = $true
$form.Controls.Add($lbCompSub)
#>
############################################################################################
##### Create Ok and Cancel Buttons
############################################################################################
$buttonPanel = New-Object Windows.Forms.Panel
$buttonPanel.Size = New-Object Drawing.Size #(400,40)
$buttonPanel.Dock = "Bottom"
## Creating the Ok Button
$okButton = New-Object Windows.Forms.Button
$okButton.Top = $cancelButton.Top ; $okButton.Left = $cancelButton.Left - $okButton.Width - 5
$okButton.Text = "Ok"
$okButton.DialogResult = "Ok"
$okButton.Anchor = "Left"
$okButton.Enabled = $false
## Creating the Cancel Button
$cancelButton = New-Object Windows.Forms.Button
$cancelButton.Left = $buttonPanel.Height - $cancelButton.Height - 10; $cancelButton.Left = $buttonPanel.Width - $cancelButton.Width - 10
$cancelButton.Text = "Cancel"
$cancelButton.DialogResult = "Cancel"
$cancelButton.Anchor = "Right"
## Add the buttons to the button panel
$buttonPanel.Controls.Add($okButton)
$buttonPanel.Controls.Add($cancelButton)
## Add the button panel to the form
$form.Controls.Add($buttonPanel)
## Set Default actions for the buttons
$form.AcceptButton = $okButton # ENTER = Ok
$form.CancelButton = $cancelButton # ESCAPE = Cancel
##################################################################################################
##### Now we do stuff
##################################################################################################
# Populate Combobox 2 When Combobox 1 changes
$ComboBox1.add_SelectedIndexChanged({
$combobox2.Items.Clear() # Clear the list
$combobox2.Text = $null # Clear the current entry
Switch ($ComboBox1.Text) {
"S01"{
$ADSiteS01 | ForEach {
$combobox2.Items.Add($_)
}
}
"S02"{
$ADSiteS02 | ForEach {
$combobox2.Items.Add($_)
}
}
"S03"{
$ADSiteS03 | ForEach {
$combobox2.Items.Add($_)
}
}
}
$labelClub.Text = $combobox1.Text + "-" + $combobox2.Text + "-" + $textBoxFPS.Text
})
$ComboBox2.add_SelectedIndexChanged({
$labelClub.Text = $combobox1.Text + "-" + $combobox2.Text + "-" + $textBoxFPS.Text
})
$textBoxFPS.add_TextChanged({
$labelClub.Text = $combobox1.Text + "-" + $combobox2.Text + "-" + $textBoxFPS.Text
})
$chkThis.Add_CheckStateChanged({
If ($chkThis.Checked) {
$okButton.enabled = $true
}
Else {
$okButton.enabled = $false
}
})
$Form.ShowDialog()
If you use an AD cmdlet to retrieve site details into an object you should easily be able to populate lists from that object using the same method you have now.