Powershell select combobox and execute a mstsc.exe - powershell

I need help and i sorry because i new in IT !
I want to make a combobox who when i select a server, have a button to open a mstsc.exe
I try fill this list in the combobox with a query like this:
$1= Get-ADComputer -Filter * -SearchBase "OU=Servers, OU=Computer, DC=example, DC=com" | select name
I try make something modificate with this example but i cant :s
[reflection.assembly]::LoadWithPartialName("System.Drawing") | Out-Null
[reflection.assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
function Button_OnClick() {
"`$combo.SelectedItem = $($combo.SelectedItem)" | Out-GridView
if ($combo.SelectedItem -eq 'Google') {
Start-Process -FilePath 'C:\Program Files\Internet Explorer\iexplore.exe' -ArgumentList 'http://www.google.com'
} elseif ($combo.SelectedItem -eq 'Microsoft') {
$IE = New-Object -ComObject 'InternetExplorer.Application'
$IE.Navigate2('http://www.microsoft.com')
$IE.Visible = $true
}
}
$combo = New-Object -TypeName System.Windows.Forms.ComboBox
$combo.Location = New-Object -TypeName System.Drawing.Point -ArgumentList 5, 5
$combo.Size = New-Object -TypeName System.Drawing.Point -ArgumentList 100, 25
$combo.Items.Add('Google') | Out-Null
$combo.Items.Add('Microsoft') | Out-Null
$combo.SelectedIndex = 0
$button = New-Object -TypeName System.Windows.Forms.Button
$button.Location = New-Object -TypeName System.Drawing.Point -ArgumentList 5, 35
$button.Size = New-Object -TypeName System.Drawing.Point -ArgumentList 100, 25
$button.Text = 'Launch in IE'
$button.Add_Click({ Button_OnClick })
$form = New-Object -TypeName System.Windows.Forms.Form
$form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
$form.MaximizeBox = $false
$form.MinimizeBox = $false
$form.Size = New-Object -TypeName System.Drawing.Point -ArgumentList 60, 105
$form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen
$form.Controls.Add($combo)
$form.Controls.Add($button)
$form.ShowDialog() | Out-Null
Thanks and sorry for my bad english

If I understand you correctly, you want to press a button and it will run a query and then dump the server names into the combo box. Simple.
You need to iterate through the names and add them to the combo box Item list, not the SelectedItem list.
$comboBox1.Items.Clear()
$1 = Get-ADComputer -Filter * -SearchBase "OU=Servers, OU=Computer, DC=example, DC=com" -Properties Name | select name
Foreach($name in $1) {
$comboBox1.Items.Add($Name.name)
}
Don't forget to clear the ComboBox before running it otherwise you will end up with duplicate entries.
EDIT:
To To run the mstsc.exe with the selected code, put this in your button function.
mstsc.exe /v:$($comboBox1.SelectedItem)

THanks Drew for help me!. I make the modification but now the powerbox just fill with one server.
This query its ok because i do in a powershell console and get me the full list:
$1 = Get-ADComputer -Filter * -SearchBase "OU=Servers, OU=xx, DC=xxx, DC=xxx" -Properties Name | select name
I copy the code who i try to fill de combobox1. Thanks again for the help!
[reflection.assembly]::LoadWithPartialName("System.Drawing") | Out-Null
[reflection.assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
$comboBox1.Items.Clear()
$1 = Get-ADComputer -Filter * -SearchBase "OU=Servers, OU=xxx, DC=xxx, DC=xxx" -Properties Name | select name
Foreach($name in $1) {
$comboBox1.Items.Add($Name.name)
}
$comboBox1 = New-Object -TypeName System.Windows.Forms.ComboBox
$comboBox1.Location = New-Object -TypeName System.Drawing.Point -ArgumentList 5, 5
$comboBox1.Size = New-Object -TypeName System.Drawing.Point -ArgumentList 100, 25
$comboBox1.Items.Add($name.name) | Out-Null
$form = New-Object -TypeName System.Windows.Forms.Form
$form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
$form.MaximizeBox = $false
$form.MinimizeBox = $false
$form.Size = New-Object -TypeName System.Drawing.Point -ArgumentList 60, 105
$form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen
$form.Controls.Add($combobox1)
$form.Controls.Add($button)
$form.ShowDialog() | Out-Null

Related

I am wanting to return to a previous funtion in Powershell, to rectify with user error if a variable is met?

The current script is as follows;
$HN = hostname
$DN = Get-ADComputer -identity $HN -Properties DistinguishedName | select-object -ExpandProperty DistinguishedName
#*
$OU = 'OU=Workstations,DC=$domain,DC=$domain,DC=$domain'
[array]$A = Get-ADOrganizationalUnit -SearchBase $OU -SearchScope OneLevel -Filter * | Select-Object -ExpandProperty Name
[array]$DropDownArray = $A | Sort-Object
function Return-DropDown {
if ($DropDown.SelectedItem -eq $B){
$DropDown.SelectedItem = $DropDown.Items[0]
$Form.Close()
}
else{
$Form.Close()
}
}
function SelectGroup{
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form = New-Object System.Windows.Forms.Form
$Form.width = 600
$Form.height = 200
$Form.Text = ”DropDown”
$DropDown = new-object System.Windows.Forms.ComboBox
$DropDown.Location = new-object System.Drawing.Size(140,10)
$DropDown.Size = new-object System.Drawing.Size(300,80)
ForEach ($Item in $DropDownArray) {
[void] $DropDown.Items.Add($Item)
}
$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 Group:"
$DropDown.Font = New-Object System.Drawing.Font("Calibri",15,[System.Drawing.FontStyle]::Bold)
$Button = new-object System.Windows.Forms.Button
$Button.Location = new-object System.Drawing.Size(140,50)
$Button.Size = new-object System.Drawing.Size(150,50)
$Button.Text = "Select an Item"
$Button.Font = New-Object System.Drawing.Font("Calibri",11,[System.Drawing.FontStyle]::Bold)
$Button.Add_Click({Return-DropDown})
$form.Controls.Add($Button)
$form.ControlBox = $false
$Button = new-object System.Windows.Forms.Button
$Button.Location = new-object System.Drawing.Size(290,50)
$Button.Size = new-object System.Drawing.Size(150,50)
$Button.Text = "Finish"
$Button.Font = New-Object System.Drawing.Font("Calibri",11,[System.Drawing.FontStyle]::Bold)
$Button.Add_Click({Move-ADObject -Identity "$DN" -TargetPath "$OU" | Return-DropDown})
$form.Controls.Add($Button)
$form.ControlBox = $false
$Form.Add_Shown({$Form.Activate()})
[void] $Form.ShowDialog()
$B = $dropdown.SelectedItem
return $B
}
$B = SelectGroup
I would like to develop this tool and add as an aditional option to return to the begining of the previous function;
$Button = new-object System.Windows.Forms.Button
$Button.Location = new-object System.Drawing.Size(290,50)
$Button.Size = new-object System.Drawing.Size(150,50)
$Button.Text = "Back"
$Button.Font = New-Object System.Drawing.Font("Calibri",11,[System.Drawing.FontStyle]::Bold)
$Button.Add_Click({Return to #* })
$form.Controls.Add($Button)
$form.ControlBox = $false
Not sure how to achieve this, hoping to find help on here.
I have looked at loops and breaks but nothing seems to fit or that i can adapt to achieve this.
If you're looking for simple repetition of the form function, you could do something like this (unless your tool hides the PowerShell window).
Do {
# Move these lines from #*
$OU = 'OU=Workstations,DC=$domain,DC=$domain,DC=$domain'
[array]$A = Get-ADOrganizationalUnit -SearchBase $OU -SearchScope
OneLevel -Filter * | Select-Object -ExpandProperty Name
[array]$DropDownArray = $A | Sort-Object
$B = SelectGroup
#{... Do Work on $B, if desired ...}
$Stop = Read-Host -Prompt 'Do you want to stop?'
} Until ($Stop -match '(Y|y|Yes|YES|yes)')
Otherwise you'll need to alter your "return-dropdown" function to not close your form and implement your "back" button another way.

How can I get rid of extra characters in TextBox?

The intent of this form is to retreive first a username then use that username to retreive an email address. it does get the address but it also retreives other characters as well. textbox3 ends up reading #{EmailAddress=first.last#domain.com}. I have tried trimming characters but that did not work.
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);'
[Console.Window]::ShowWindow([Console.Window]::GetConsoleWindow(), 0)
<#
.NAME
Template
#>
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$Form = New-Object system.Windows.Forms.Form
$Form.ClientSize = New-Object System.Drawing.Point(400,400)
$Form.text = "Form"
$Form.TopMost = $false
$TextBox1 = New-Object system.Windows.Forms.TextBox
$TextBox1.multiline = $false
$TextBox1.width = 100
$TextBox1.height = 20
$TextBox1.location = New-Object System.Drawing.Point(61,52)
$TextBox1.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$TextBox2 = New-Object system.Windows.Forms.TextBox
$TextBox2.multiline = $false
$TextBox2.width = 100
$TextBox2.height = 20
$TextBox2.location = New-Object System.Drawing.Point(219,52)
$TextBox2.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$TextBox3 = New-Object system.Windows.Forms.TextBox
$TextBox3.multiline = $false
$TextBox3.width = 100
$TextBox3.height = 20
$TextBox3.location = New-Object System.Drawing.Point(61,130)
$TextBox3.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Button1 = New-Object system.Windows.Forms.Button
$Button1.text = "button"
$Button1.width = 60
$Button1.height = 30
$Button1.location = New-Object System.Drawing.Point(228,127)
$Button1.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$Button1.Add_Click({getacctname})
$Form.controls.AddRange(#($TextBox1,$TextBox2,$TextBox3,$Button1))
#region Logic
function getacctname {
$fname = $TextBox1.Text
$lname = $TextBox2.Text
$User.Text = Get-ADUser -Filter "GivenName -eq '$fname' -and SurName -eq '$lname'" |
Select-Object -ExpandProperty 'SamAccountName' |
Out-Gridview -Title 'Windows Logon' -PassThru
$TextBox3.Text = Get-ADUser -identity $User.text -Properties * | select EmailAddress
}
#endregion
[void]$Form.ShowDialog()
There are two issues with your code:
As explained in a comment, you need to get the value from the EmailAddress property of your object, otherwise, because the .Text property value can only be a string, what you will see as a result is a string representation of a PSCustomObject.
The assignment of $User.Text is invalid and will produce an error unless you're not showing us your actual code. The $User variable not defined hence cannot have a .Text property. Trying to assign anything to it will produce an error such as:
The property 'Text' cannot be found on this object. Verify that the property exists and can be set.
How should your function to solve both issues:
function getacctname {
$fname, $lname = $TextBox1.Text.Trim(), $TextBox2.Text.Trim()
$TextBox3.Text = Get-ADUser -Filter "GivenName -eq '$fname' -and SurName -eq '$lname'" -Properties mail |
Select-Object SamAccountName, mail |
Out-Gridview -Title 'Windows Logon' -PassThru |
Select-Object -ExpandProperty mail
}
As aside, I would recommend you to make $TextBox3 a ReadOnly TextBox:
$TextBox3.ReadOnly = $true

Need help gui background-job double-hop issue and script freezing

I'm having an issue with double hopping scriptblock for background job that either does nothing or freezes the script. Explenation below.
The idea for the script is to get a list of files (very large count, ~200k) and then process them in three individual ways (get hashcodes and get true duplicates, compare filenames and get pseudo duplicates, get zero length files). At this moment I'm working on hashes. The result of $job1 is a string (array?) that cannot be piped to get-filehash. This results in $job2 looping through each string in order to get hashes. As background-jobs work on scriptblocks and foreach loop has scriptblock component a double hop is created. I've worked around that by using invoke-command combined with [scriptblock]::Create() method inside job scriptblock. That unfortunately freezes the form. My question to you is as follows. How do I force $job1 result to be of system.io.fileinfo type OR how do I unfreeze script while Invoke-command is in progress?
Add-Type -AssemblyName System.Windows.Forms
add-type -AssemblyName system.drawing
[System.Windows.Forms.Application]::EnableVisualStyles()
$path = "C:\"
$window = New-Object system.Windows.Forms.Form
$window.Size = New-Object system.Drawing.Size #(400,400)
$window.StartPosition = "CenterScreen"
$window.Font = New-Object System.Drawing.Font("Calibri",11,[System.Drawing.FontStyle]::Bold)
$window.Text = "STARTING UP"
$ProgressBar1 = New-Object System.Windows.Forms.ProgressBar
$ProgressBar1.Location = New-Object System.Drawing.Point(10, 10)
$ProgressBar1.Size = New-Object System.Drawing.Size(365, 20)
$ProgressBar1.Style = "Marquee"
$ProgressBar1.MarqueeAnimationSpeed = 20
$ProgressBar1.UseWaitCursor = $true
$ProgressBar1.Visible = $false
$button = New-Object System.Windows.Forms.Button
$button.size = New-Object system.drawing.size #(50,50)
$button.Location = New-Object System.Drawing.Point(20, 70)
$button.Text = "TEST"
$window.Controls.add($button)
$label = New-Object System.Windows.Forms.Label
$label.Size = New-Object System.Drawing.Size #(100, 50)
$label.Location = New-Object System.Drawing.Point (80, 70)
$label.BorderStyle = 'Fixed3D'
$label.ForeColor = 'green'
$label.TextAlign = 'middlecenter'
$window.Controls.Add($label)
$timer = New-Object System.Windows.Forms.Timer
$timer.Interval = 1000
$timer.add_Tick({$script:time2 =((get-date)-$script:time1).ToString("hh\:mm\:ss")
$label2.text = $script:time2
})
$button.add_Click(
{$1 = Get-Date
$Script:time1 = Get-Date
$timer.start()
$ProgressBar1.BringToFront()
$ProgressBar1.Show()
$this.Enabled = $false
$job = Start-Job -ScriptBlock {
Get-ChildItem -File -recurse $HOME -ErrorAction SilentlyContinue|select -ExpandProperty FullName
}
while($job.State -eq 'Running') {
[System.Windows.Forms.Application]::DoEvents()
}
$script:asd = $job | Receive-Job #-AutoRemoveJob -Wait
$ProgressBar1.Hide()
$this.Enabled = $true
$2 = ((get-date) - $1).ToString("hh\:mm\:ss")
$label.text = $2
$timer.stop()
}
)
$button2 = New-Object System.Windows.Forms.Button
$button2.Size = New-Object System.Drawing.Size #(50, 50)
$button2.Location = New-Object System.Drawing.Point (200, 70)
$button2.Text = 'Exit'
$window.Controls.Add($button2)
$button2.add_Click({$window.Close()})
$button3 = new-object System.Windows.Forms.Button
$button3.Size = New-Object System.Drawing.Size #(50, 50)
$button3.Location = New-Object System.Drawing.Point (20, 200)
$button3.Text = "Start"
$window.Controls.Add($button3)
$button3.add_Click({
$sb = foreach ($qwe in $Script:asd){Get-FileHash $qwe -Algorithm MD5|select -ExpandProperty Hash -OutVariable +Script:tester}
$ProgressBar2.BringToFront()
$ProgressBar2.Show()
$this.Enabled = $false
$job2 = start-job -Name 'asd' -scriptblock {
param($sb)
$sb = [scriptblock]::Create($sb)
Invoke-command -ScriptBlock $sb
}
while($job2.State -eq 'Running') {
[System.Windows.Forms.Application]::DoEvents()
}
Write-Host $Script:tester
$ProgressBar2.Hide()
$this.Enabled = $true
})
$label2 = New-Object System.Windows.Forms.Label
$label2.size = New-Object System.Drawing.Size #(100, 50)
$label2.Location = New-Object System.Drawing.Point (80, 200)
$label2.BorderStyle = 'Fixed3D'
$label2.ForeColor = 'green'
$label2.TextAlign = 'middlecenter'
$window.Controls.Add($label2)
$ProgressBar2 = New-Object System.Windows.Forms.ProgressBar
$ProgressBar2.Location = New-Object System.Drawing.Point(10, 330)
$ProgressBar2.Size = New-Object System.Drawing.Size(365, 20)
$ProgressBar2.Style = "Marquee"
$ProgressBar2.MarqueeAnimationSpeed = 20
$ProgressBar2.UseWaitCursor = $true
$ProgressBar2.Visible = $false
$window.Controls.Add($ProgressBar2)
$groupbox = New-Object System.Windows.Forms.GroupBox
$groupbox.size = New-Object system.drawing.size #(377, 365)
$groupbox.Location = New-Object System.Drawing.point (4, -5)
$window.Controls.Add($groupbox)
$window.Controls.Add($ProgressBar1)
$window.ShowDialog()|out-null
For anyone interested. The answer was piping $job results to set-variable - $job|Wait-job|Receive-Job|Set-Variable -Name JOB_RESULT -Scope Script.
Then using $using: scope in $job2 scriptblock - $job2 = start-job -scriptblock { $using:JOB_RESULT|Get-FileHash -Algorithm MD5}

Powershell if else statement

I am having some difficulties with my Powershell script. With this script I am able to enable disabled AD accounts. It works, but I am receiving the wrong output. Accounts got enabled, but still receive the output from the else statement 'Account has not been enabled'. Anyone who can help me? Thanks!
Add-Type -AssemblyName System.Windows.Forms
$SystemInfoForm = New-Object System.Windows.Forms.Form
$SystemInfoForm.ClientSize = "300,100"
$SystemInfoForm.Text = "Enable AD Accounts"
$SystemInfoForm.BackColor = "#ffffff"
$SystemInfoForm.StartPosition = "CenterScreen"
$objIcon = New-Object system.drawing.icon ("C:\Temp\System Info.ico")
$SystemInfoForm.Icon = $objIcon
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20)
$label.Size = New-Object System.Drawing.Size(280,20)
$label.Text = 'Please enter the disabled AD account below:'
$SystemInfoForm.Controls.Add($label)
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(10,40)
$textBox.Size = New-Object System.Drawing.Size(260,20)
$textBox.Text = "Enter AD account..."
$SystemInfoForm.Controls.Add($textBox)
$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(10,70)
$okButton.Size = New-Object System.Drawing.Size(75,23)
$okButton.Text = 'OK'
$okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$okButton.Add_Click(
{
$Username = $textBox.Text
if (Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount)
{
[System.Windows.MessageBox]::Show("$Username has been enabled.")
}
else
{
[System.Windows.MessageBox]::Show("$Username has not been enabled.")
}
}
)
$SystemInfoForm.Controls.Add($okButton)
[void]$SystemInfoForm.ShowDialog()
Regards,
Ralph
Enable-ADAccount doesn't return any output by default, so the entire pipeline expression:
Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount
... will evaluate to nothing - and all of that nothing evaluates to $false in your if condition.
Use a try/catch block to catch errors from Enable-ADAccount and then alert the based on that:
try {
Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount -ErrorAction Stop
# We got this far because Enable-ADAccount didn't throw any errors
[System.Windows.MessageBox]::Show("$Username has been enabled.")
}
catch {
[System.Windows.MessageBox]::Show("$Username has not been enabled.")
}
Alternatively use the -PassThru switch with Enable-ADAccount to have it return the account, then inspect that:
$enabledAccount = Search-ADAccount -AccountDisabled | Where-Object {($_.SamAccountName -eq "$Username")} | Enable-ADAccount -PassThru
if($enabledAccount.Enabled){
[System.Windows.MessageBox]::Show("$Username has been enabled.")
}
else {
[System.Windows.MessageBox]::Show("$Username has not been enabled.")
}

ComboBox.SelectedItem is null

I populated a combobox with AD SamAccountName items. When selecting one of the items, one can push a button in order to retrieve information from that account. However, when clicking the button I receive the below error:
Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the command again.
The command the error refers to is:
$Label_User_ItemContent.Text = (Get-ADUser -Identity $ComboBox.SelectedItem).SamAccountName
The crucial part of the code is:
$ComboBox = New-Object -TypeName System.Windows.Forms.ComboBox
$ComboBox.Width = 300
$ComboBox.Location = New-Object -TypeName System.Drawing.Point(250, 25)
$Users = Get-ADUser -Filter * | Where-Object {$_.SamAccountName -match '^adminA'}
ForEach ($User in $Users){
$ComboBox.Items.Add($User.SamAccountName)
}
$ComboBox.SelectedIndex = 1
$MainWindow.Controls.Add($ComboBox)
$Button_Check_TEST = New-Object -TypeName System.Windows.Forms.Button
$Button_Check_TEST.Location = New-Object -TypeName System.Drawing.Size(350, 150)
$Button_Check_TEST.Size = New-Object -TypeName System.Drawing.Size(150, 50)
$Button_Check_TEST.Text = 'Check'
$MainWindow.Controls.Add($Button_Check_TEST)
$Button_Check_TEST.Add_Click({
Try{
$Label_User_ItemContent.Text = (Get-ADUser -Identity $ComboBox.SelectedItem).SamAccountName
}
Catch{
Write-Verbose -Verbose $_.Exception.Message
}
})
The problem is, that I need two layers. Basically, there should be a menu with four different options, one of them is 'User'. When clicking on 'User' the ComboBox and the 'Click'-Button shall appear.
Using the code above without the 'User'-Button works fine.
Question: Why does the ComboBox.SelectedItem not work when I use a button to 'create' the ComboBox?
The complete code is below:
$font = New-Object -TypeName System.Drawing.Font("Times New Roman", 18, [System.Drawing.FontStyle]::Bold)
$MainWindow = New-Object -TypeName System.Windows.Forms.Form
$MainWindow.Text = 'PIM v10 Administrator Window'
$MainWindow.Width = 600
$MainWindow.Height = 555
$MainWindow.AutoSize = $true
$Button_User = New-Object -TypeName System.Windows.Forms.Button
$Button_User.Location = New-Object -TypeName System.Drawing.Size(25, 25)
$Button_User.Size = New-Object -TypeName System.Drawing.Size(200, 75)
$Button_User.Text = 'User'
$Button_User.Font = $font
$MainWindow.Controls.Add($Button_User)
$Button_User.Add_Click({
$Label_User = New-Object -TypeName System.Windows.Forms.Label
$Label_User.Text = 'Given Name:'
$Label_User.Location = New-Object -TypeName System.Drawing.Point(250, 50)
$Label_User.AutoSize = $true
$MainWindow.Controls.Add($Label_User)
$Label_User_ItemContent = New-Object -TypeName System.Windows.Forms.Label
$Label_User_ItemContent.Text = ''
$Label_User_ItemContent.Location = New-Object -TypeName System.Drawing.Point(250, 100)
$MainWindow.Controls.Add($Label_User_ItemContent)
$ComboBox = New-Object -TypeName System.Windows.Forms.ComboBox
$ComboBox.Width = 300
$ComboBox.Location = New-Object -TypeName System.Drawing.Point(250, 25)
$Users = Get-ADUser -Filter * | Where-Object {$_.SamAccountName -match '^adminA'}
ForEach ($User in $Users){
$ComboBox.Items.Add($User.SamAccountName)
}
$ComboBox.SelectedIndex = 1
$MainWindow.Controls.Add($ComboBox)
$Button_Check_TEST = New-Object -TypeName System.Windows.Forms.Button
$Button_Check_TEST.Location = New-Object -TypeName System.Drawing.Size(350, 150)
$Button_Check_TEST.Size = New-Object -TypeName System.Drawing.Size(150, 50)
$Button_Check_TEST.Text = 'Check'
$MainWindow.Controls.Add($Button_Check_TEST)
$Button_Check_TEST.Add_Click({
Try{
$Label_User_ItemContent.Text = (Get-ADUser -Identity $ComboBox.SelectedItem).SamAccountName
}
Catch{
Write-Verbose -Verbose $_.Exception.Message
}
})
if (-not ($ComboBox.SelectedItem -eq $null)){
$Label_User_ItemContent.Text = (Get-ADUser -Identity $ComboBox.SelectedItem).SamAccountName
}
else {
Write-Host -Object "Object is null"
}
})
$MainWindow.ShowDialog()
So whats happening is you are creating variables in the wrong scope
$Button_User.Add_Click({
$ComboBox = New-Object -TypeName System.Windows.Forms.ComboBox
$Label_User_ItemContent = New-Object -TypeName System.Windows.Forms.Label
$MainWindow.Controls.Add($ComboBox)
$Label_User_ItemContent = New-Object -TypeName System.Windows.Forms.Label
$Button_Check_TEST.Add_Click({
$Label_User_ItemContent.Text = (Get-ADUser -Identity
$ComboBox.SelectedItem).SamAccountName
)}
})
Since you are creating the Combo and the Lable inside a Add_click action. Those Values only exist when the action is taken and in the $MainWindows.Controls. The items are then cleared from memory
When you run the next action $Button_Check_TEST.Add_Click() since the variables are cleared then $ComboBox and $Label_User_ItemContent equal nothing.
A fix would be to place them outside the $Button_User.Add_Click() event
$ComboBox = New-Object -TypeName System.Windows.Forms.ComboBox
$Label_User_ItemContent = New-Object -TypeName System.Windows.Forms.Label
$Button_User.Add_Click({
$MainWindow.Controls.Add($ComboBox)
$Label_User_ItemContent = New-Object -TypeName System.Windows.Forms.Label
$Button_Check_TEST.Add_Click({
$Label_User_ItemContent.Text = (Get-ADUser -Identity
$ComboBox.SelectedItem).SamAccountName
)}
})
Here is the whole script in working condition now
$font = New-Object -TypeName System.Drawing.Font("Times New Roman", 18, [System.Drawing.FontStyle]::Bold)
$MainWindow = New-Object -TypeName System.Windows.Forms.Form
$MainWindow.Text = 'PIM v10 Administrator Window'
$MainWindow.Width = 600
$MainWindow.Height = 555
$MainWindow.AutoSize = $true
$Button_User = New-Object -TypeName System.Windows.Forms.Button
$Button_User.Location = New-Object -TypeName System.Drawing.Size(25, 25)
$Button_User.Size = New-Object -TypeName System.Drawing.Size(200, 75)
$Button_User.Text = 'User'
$Button_User.Font = $font
$MainWindow.Controls.Add($Button_User)
$ComboBox = New-Object -TypeName System.Windows.Forms.ComboBox
$Label_User_ItemContent = New-Object -TypeName System.Windows.Forms.Label
$Button_User.Add_Click({
$Label_User = New-Object -TypeName System.Windows.Forms.Label
$Label_User.Text = 'Given Name:'
$Label_User.Location = New-Object -TypeName System.Drawing.Point(250, 50)
$Label_User.AutoSize = $true
$MainWindow.Controls.Add($Label_User)
$Label_User_ItemContent.Text = ''
$Label_User_ItemContent.Location = New-Object -TypeName System.Drawing.Point(250, 100)
$MainWindow.Controls.Add($Label_User_ItemContent)
$ComboBox.Width = 300
$ComboBox.Location = New-Object -TypeName System.Drawing.Point(250, 25)
$Users = Get-ADUser -Filter * | Where-Object {$_.SamAccountName -match '^adminA'}
$MainWindow.Controls.Add($ComboBox)
ForEach ($User in $Users){
$ComboBox.Items.Add($User.SamAccountName)
}
$MainWindow.Controls.Add($ComboBox)
$ComboBox.SelectedIndex = 0
$Button_Check_TEST = New-Object -TypeName System.Windows.Forms.Button
$Button_Check_TEST.Location = New-Object -TypeName System.Drawing.Size(350, 150)
$Button_Check_TEST.Size = New-Object -TypeName System.Drawing.Size(150, 50)
$Button_Check_TEST.Text = 'Check'
$MainWindow.Controls.Add($Button_Check_TEST)
$Button_Check_TEST.Add_Click({
Try{
$Label_User_ItemContent.Text = (Get-ADUser -Identity $ComboBox.SelectedItem).SamAccountName
}
Catch{
Write-Verbose -Verbose $_.Exception.Message
}
})
if (-not ($ComboBox.SelectedItem -eq $null)){
$Label_User_ItemContent.Text = (Get-ADUser -Identity $ComboBox.SelectedItem).SamAccountName
}
else {
Write-Host -Object "Object is null"
}
})
$MainWindow.ShowDialog()