Show a list when a choice is made - powershell

I'm trying to work around a script Under Windows.Form and I'm a little bit stuck.
I'd like to be able a specific list appears depending on the choice made from the first list, which means that at the start of the script, only one list has to appears and many other available depending of the choice made.
Here's the full script for reference
#Open a Window.
[Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$form = New-Object Windows.Forms.Form
$form.text = "Contrôles"
$form.Size = New-Object System.Drawing.Size(1000,700)
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(75,150)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = 'OK'
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(150,150)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = 'Cancel'
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$form.CancelButton = $CancelButton
$form.Controls.Add($CancelButton)
#Create the Data table (DataTable).
$table1 = New-Object system.Data.DataTable
$table2 = New-Object system.Data.DataTable
#Define the 2 column (Name, Type).
$colonne1 = New-Object system.Data.DataColumn Choice,([string])
$colonne2 = New-Object system.Data.DataColumn Choice,([string])
#Create columns in the data table.
$table1.columns.add($colonne1)
$table2.columns.add($colonne2)
#Add the data line by line in the data table.
$ligne = $table1.NewRow() #Creation of the new row.
$ligne.Choice = "Service" #In the column Choice we put the value we want.
$table1.Rows.Add($ligne) #Add a line in the data table.
$ligne = $table1.NewRow()
$ligne.Choice = "Software"
$table1.Rows.Add($ligne)
$ligne = $table1.NewRow()
$ligne.Choice = "Other"
$table1.Rows.Add($ligne)
#Add the data line by line in the data table.
$ligne = $table2.NewRow() #Creation of the new row.
$ligne.Choice = "Service Enable" #In the column Choice we put the value we want.
$table2.Rows.Add($ligne) #Add a line in the data table.
$ligne = $table2.NewRow()
$ligne.Choice = "Service Disable"
$table2.Rows.Add($ligne)
$ligne = $table2.NewRow()
$ligne.Choice = "Other"
$table2.Rows.Add($ligne)
#Create the View.
$vu1 = New-Object System.Data.DataView($table1)
$vu1.Sort="Choice ASC" #Tri la colonne "Extension" par ordre croissant.
$vu2 = New-Object System.Data.DataView($table2)
$vu2.Sort="Choice ASC"
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(650,50)
$label.Size = New-Object System.Drawing.Size(280,35)
$label.Text = 'Please enter the information in the space below:'
$form.Controls.Add($label)
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(650,100)
$textBox.Size = New-Object System.Drawing.Size(260,20)
$form.Controls.Add($textBox)
#Create the Drop-down list (ComboBox).
$liste1 = New-Object System.Windows.Forms.Combobox
$liste1.Location = New-Object Drawing.Point 20,50
$liste1.Size = New-Object System.Drawing.Size(150, 50)
$liste1.DropDownStyle = "DropDownList"
$liste2 = New-Object System.Windows.Forms.Combobox
$liste2.Location = New-Object Drawing.Point 350,50
$liste2.Size = New-Object System.Drawing.Size(150, 50)
$liste2.DropDownStyle = "DropDownList"
#Associate the Data to the Drop-down list
#To do so, we create a "Binding Context".
$liste1.BindingContext = New-Object System.Windows.Forms.BindingContext
$liste1.DataSource = $vu1 #Assigne the view that contains the sorted Data.
$liste1.DisplayMember = "Choice" #Column that will be displayed (Choice).
$liste2.BindingContext = New-Object System.Windows.Forms.BindingContext
$liste2.DataSource = $vu2 #Assigne the view that contains the sorted Data.
$liste2.DisplayMember = "Choice" #Column that will be displayed (Choice).
#Attach the control to the window.
$form.controls.add($liste1)
$form.controls.add($liste2)
#Show everything.
$form.Add_Shown({$textBox.Select()})
$result = $form.ShowDialog()
#Work the code arround.
if ($liste1.DisplayMember= "Service Enable")
{set-service -name RemoteRegistry -ComputerName $textBox.Text -StartupType Automatic}
if ($liste1.DisplayMember = "Service Disable")
{set-service -name RemoteRegistry -ComputerName $textBox.Text -StartupType Automatic}
Write-Host "ComboBox = " $liste1.DisplayMember
Write-Host "ComboBox = " $liste2.selectedvalue
#Fin.
If anybody have an idea where I could look, it would be great.
Thanks you
Nad

1. You have no form / trigger events in your code.
2. You don't have the correct GUI objects in your code to hold a list /
record result.
A form is just a container to hold elements until you add the code behind to make it do something. You have to have a proper GUI object to send that result to.
I am not sure if you are doing this all by hand in the ISE or VSCode or Notepad or whatever, but this is a good first effort. However, what you show, seems to indicate you are not really up to speed on GUI development / general app dev work, as what you are doing is not really unique to PowerShell, but something required for any app development client or web.
So, really, spend some time studying / reviewing general WPF/Winforms development and that form event stuff will be covered.
As for your use case, you need:
Define the list GUI object (multiline, ListBox, ListView, datagrid) to hold the results (synch'ing combox boxes mean adding and removing elements on event actions)
Define what that list is (text files, db read etc)
On the click, change or other form event, read from that list and populate
the GUI list object
There are many examples of this on this site and all over the web.
Here a good video on GUI development with PowerShell:
powershell populate combobox basing on the selected item on another combobox
From the above discussion (not something to just add to your code without understanding the what's and the why's):
Use a ComboBox.SelectionChangeCommitted Event:
"Occurs when the user changes the selected item and that change is displayed in the ComboBox"
$combobox2_SelectionChangeCommitted={
$Mailboxes = Get-Mailbox -OrganizationalUnit $ClientSelected
foreach ($mailbox in $Mailboxes)
{
$CurrentMailbox = "{0} ({1})" -f $mailbox.Name, $mailbox.Alias
Load-ComboBox $combobox2 $CurrentMailbox -Append
}
}
Use a button:
$button1_Click={
$Mailboxes = Get-Mailbox -OrganizationalUnit $ClientSelected
foreach ($mailbox in $Mailboxes)
{
$CurrentMailbox = "{0} ({1})" -f $mailbox.Name, $mailbox.Alias
Load-ComboBox $combobox2 $CurrentMailbox -Append
}
}
Lastly, using this …
Write-Host "ComboBox = " $liste1.DisplayMember
Write-Host "ComboBox = " $liste2.selectedvalue
… is not something one would do, because the console is not opened to see these results and Write-Host should be avoided except for when using console only text colorizations of other console only formatting scenarios, it also empties the display buffer, so it cannot be sent to anything else. Also, you don't have a GUI object called 'ComboBox' anywhere on the form, so it's not serving any purpose for your use case.

After some times and research, I managed to find what I needed exactly.
This might help people who stumble upon the post so here a small part of what I found
function Service()
{if ($ListBox1.SelectedItem -eq 'Enable Services')
{
$form.Controls.Add($Label3)
$form.Controls.add($ListBox2)
$form.Controls.Add($Label4)
$form.Controls.Add($textBox)
$form.Controls.Add($Button2)
$form.Controls.Add($Button3)
}
I create firstly a Function with a name, in which will countain the condition of what I'd like to happen when a choice is made in my listbox "ComboBox"
$button1.add_Click({ Service })
Then I call that function from a button I Added, in which other Boxes will appear upon click on that button.
It is not very different from #Postanote's answer but that was the solution I'm more at ease with.

Related

How to ensure Forms are the top window

I have a PS script that implements System.Windows.Forms in order to query technicians for some data.
I create the forms and set both .Topmost and .TopLevel to true in an attempt to have them show up over the Powershell window, but they continue to (for some reason inconsistently) appear behind the Powershell window. This slows down the process and is confusing in its inconsistency.
If anyone knows how to ensure these windows stay top without a mountain of code larger than the script itself that would be incredibly useful. I'll include the code I use to build one of the basic forms below.
Any simple solution that will allow these Forms to appear over the Powershell window is appreciated. It could even just minimize the PS window, but I don't want to launch without the window as we need it open. Thanks.
$form.Text = 'Computer Name Entry'
$form.Size = New-Object System.Drawing.Size(550,400)
$form.StartPosition = 'CenterScreen'
$okButton = New-Object System.Windows.Forms.Button
$okButton.Location = New-Object System.Drawing.Point(75,300)
$okButton.Size = New-Object System.Drawing.Size(75,23)
$okButton.Text = 'OK'
$okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $okButton
$form.Controls.Add($okButton)
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20)
$label.Size = New-Object System.Drawing.Size(400,40)
$label.Text = 'Text is here:'
$form.Controls.Add($label)
$textBox = New-Object System.Windows.Forms.TextBox
$textBox.Location = New-Object System.Drawing.Point(10,70)
$textBox.Size = New-Object System.Drawing.Size(400,20)
$form.Controls.Add($textBox)
$form.Topmost = $true
$form.TopLevel = $true
$form.Add_Shown({$textBox.Select()})
$result = $form.ShowDialog()
if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{
Do-Stuff
}
The easiest way I know of forcing the form to be topmost is to open it with a new temporary form that is TopMost as parameter for ShowDialog().
First, from your code remove the lines $form.Topmost = $true and $form.TopLevel = $true
Next, show your form like this:
# force the dialog TopMost by creating a temporary parent window for this form
$result = $form.ShowDialog((New-Object System.Windows.Forms.Form -Property #{TopMost = $true }))
Another way of doing this is to use a piece of C# to return a windowhandle which implements the IWin32Window interface.
Then use this handle as the owner window for this form in the .ShowDialog() method of the form.
For this method, also remove the lines $form.Topmost = $true and $form.TopLevel = $true from your original code.
$iWin32Code = #"
using System;
using System.Windows.Forms;
public class Win32Window : IWin32Window {
public Win32Window(IntPtr handle) {
Handle = handle;
}
public IntPtr Handle { get; private set; }
}
"#
if (-not ([System.Management.Automation.PSTypeName]'Win32Window').Type) {
Add-Type -TypeDefinition $iWin32Code -ReferencedAssemblies System.Windows.Forms.dll
}
Now, using that code, create a handle for the currently running PowerShell process
# get the owner handle from this PowerShell process
$ownerHandle = New-Object Win32Window -ArgumentList ([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)
# and use that in the ShowDialog method as argument
$result = $form.ShowDialog($ownerHandle)
P.S. do not forget to clear your form from memory after you are done with it by calling
$form.Dispose()

List AD Users in List Box in Powershell

I'm currently making my own administration tool and one function should end up being "Disable Account" (Active Directory User).
The Code I currently have is the following:
#Assemblies
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
#Frame
$frmDisableUser = New-Object system.Windows.Forms.Form
$frmDisableUser.ClientSize = New-Object System.Drawing.Point(378,99)
$frmDisableUser.text = "Disable User"
$frmDisableUser.TopMost = $false
$frmDisableUser.BackColor = [System.Drawing.ColorTranslator]::FromHtml("#ffffff")
$frmDisableUser.TopMost = $false
$frmDisableUser.FormBorderStyle = "FixedSingle"
$frmDisableUser.startposition = "CenterScreen"
$frmDisableUser.MaximizeBox = $false
#AD Users Listbox
$lstADUsers = New-Object system.Windows.Forms.ListBox
$lstADUsers.width = 356
$lstADUsers.height = 20
$lstADUsers.location = New-Object System.Drawing.Point(9,18)
$lstADUsers.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
#Disable Account Button
$btnDisableAccount = New-Object system.Windows.Forms.Button
$btnDisableAccount.text = "Disable"
$btnDisableAccount.width = 100
$btnDisableAccount.height = 30
$btnDisableAccount.location = New-Object System.Drawing.Point(265,53)
$btnDisableAccount.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$btnDisableAccount.Add_Click({
})
#Adds all elements into th eframe
$frmDisableUser.controls.AddRange(#($lstADUsers,$btnDisableAccount))
#Shows the frame
$frmDisableUser.ShowDialog()
The Command I use to get all AD Users as an output is the following:
Get-ADUser -Filter {(Enabled -eq "true")} | Select-Object Name
I think the easiest way is to make it using arrays but I'm not really familiar with arrays to be honest... I'd be very happy if you could help me!
Thanks for your time!
You can add items to the listbox with
$lstADUsers.Items.Add()
I've updated your code to demonstrate this.
#Assemblies
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
#Frame
$frmDisableUser = New-Object system.Windows.Forms.Form
$frmDisableUser.ClientSize = New-Object System.Drawing.Point(388,299)
$frmDisableUser.text = "Disable User"
$frmDisableUser.TopMost = $false
$frmDisableUser.BackColor = [System.Drawing.ColorTranslator]::FromHtml("#ffffff")
$frmDisableUser.TopMost = $false
$frmDisableUser.FormBorderStyle = "FixedSingle"
$frmDisableUser.startposition = "CenterScreen"
$frmDisableUser.MaximizeBox = $false
#AD Users Listbox
$lstADUsers = New-Object system.Windows.Forms.ListBox
$lstADUsers.width = 356
$lstADUsers.height = 220
$lstADUsers.location = New-Object System.Drawing.Point(9,18)
$lstADUsers.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$lstADUsers.AutoSize = $false
Get-ADUser -Filter {(Enabled -eq "true")} | foreach{[void]$lstADUsers.Items.Add($_.name)}
#Disable Account Button
$btnDisableAccount = New-Object system.Windows.Forms.Button
$btnDisableAccount.text = "Disable"
$btnDisableAccount.width = 100
$btnDisableAccount.height = 30
$btnDisableAccount.location = New-Object System.Drawing.Point(265,249)
$btnDisableAccount.Font = New-Object System.Drawing.Font('Microsoft Sans Serif',10)
$btnDisableAccount.Add_Click({
})
#Adds all elements into th eframe
$frmDisableUser.controls.AddRange(#($lstADUsers,$btnDisableAccount))
#Shows the frame
$frmDisableUser.ShowDialog()
Note the cast to [void] - this is to suppress the output from the .Add() method. It emits the the index number for that item in the array.
I also suggest you check out https://poshgui.com/ if you haven't already. It can help you not only design forms but also learn how to interact with the GUI components.
The Items property of a ListBox (which is an ObjectCollection object) has a method called AddRange with which you can enter an array.
Just get a string array of usernames and enter it in one go.
To make the list better readable, sort it alphabetically. You could also set the 'Sorted' property of the Listbox to $true, but sorting before adding to the listbox is more efficient.
$users = (Get-ADUser -Filter "Enabled -eq 'True'").Name | Sort-Object
Next add the array to the listbox
$lstADUsers.Items.AddRange($users)
P.S. If you need to refresh the listbox data with the result of a new call to Get-ADUser, clear the listbox items first with $lstADUsers.Items.Clear()

How to create CheckBox automatically using PowerShell?

I want to create checkbox automatically consider to the total a file inside a folder I selected.
In my script, the checkbox always create one checkbox, but my file more than one. And the checkbox always appear before I select the folder from listbox. Please give me advice if anyone know about this, Thank you so much.
This is the result look like
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Select a Computer"
$objForm.Size = New-Object System.Drawing.Size(500,700)
$objForm.StartPosition = "CenterScreen"
$objForm.Text = "Test"
$objListBox = New-Object System.Windows.Forms.ListBox
$objListBox.Location = New-Object System.Drawing.Size(10,70)
$objListBox.Size = New-Object System.Drawing.Size(260,30)
$objListBox.Height = 250
$objListBox.add_SelectedIndexChanged($SelectedFile)
$objForm.Controls.Add($objListBox)
$objChktBox = New-Object System.Windows.Forms.CheckBox
$objChktBox.Location = New-Object System.Drawing.Size(10,400)
$objChktBox.Size = New-Object System.Drawing.Size(400,3000)
$objChktBox.Height = 200
$objForm.Controls.Add($objChktBox)
# Populate list.
#(Get-ChildItem -Directory ".\").Name | ForEach-Object {[void] $objListBox.Items.Add($_)}
$SelectedFile=
{
$objChktBox.Text = (Get-ChildItem $objListbox.SelectedItem)
}
$objForm.ShowDialog()

Creating a powershell GUI that calls seperate powershell scripts

Can someone point me in the right direction? I want to create a powershell script that opens up to a module with check boxes and fields.
Say I have individual powershell scripts that I want to run on a server. I want to be able to have them all in the window and be able to toggle them on and off (with a checkbox) as needed. Here is an example of some code and the GUI I want to make.
So each check box would add the respective code to the list to run. I should be able to get the GUI setup. Its the run button, getting the checkbox to call up a script and the variable field I'm not too sure about.
Screenshot
Here is the code I am working with
#This creates the form and sets its size and position
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Server Setup / Install Roles"
$objForm.Size = New-Object System.Drawing.Size(800,800)
#This creates a checkbox called Set Remote Execution to: unrestricted
$objSet_RECheckbox = New-Object System.Windows.Forms.Checkbox
$objSet_RECheckbox.Location = New-Object System.Drawing.Size(10,10)
$objSet_RECheckbox.Size = New-Object System.Drawing.Size(500,20)
$objSet_RECheckbox.Text = "Set Remote Execution to: unrestricted"
$objSet_RECheckbox.TabIndex = 1
$objForm.Controls.Add($objSet_RECheckbox)
#This creates a checkbox called Change time zone
$objTimeCheckbox = New-Object System.Windows.Forms.Checkbox
$objTimeCheckbox.Location = New-Object System.Drawing.Size(10,30)
$objTimeCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objTimeCheckbox.Text = "Change time zone"
$objTimeCheckbox.TabIndex = 2
$objForm.Controls.Add($objTimeCheckbox)
#This creates a checkbox called Install DNS Role
$objDNSCheckbox = New-Object System.Windows.Forms.Checkbox
$objDNSCheckbox.Location = New-Object System.Drawing.Size(10,50)
$objDNSCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objDNSCheckbox.Text = "Install DNS Role"
$objDNSCheckbox.TabIndex = 3
$objForm.Controls.Add($objDNSCheckbox)
#This creates a checkbox called Install DHCP Role
$objDHCPCheckbox = New-Object System.Windows.Forms.Checkbox
$objDHCPCheckbox.Location = New-Object System.Drawing.Size(10,70)
$objDHCPCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objDHCPCheckbox.Text = "Install DHCP Role"
$objDHCPCheckbox.TabIndex = 4
$objForm.Controls.Add($objDHCPCheckbox)
#This creates a checkbox called Install Print Role
$objPrintCheckbox = New-Object System.Windows.Forms.Checkbox
$objPrintCheckbox.Location = New-Object System.Drawing.Size(10,90)
$objPrintCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objPrintCheckbox.Text = "Install Print Role"
$objPrintCheckbox.TabIndex = 5
$objForm.Controls.Add($objPrintCheckbox)
#This creates a checkbox called Install AD and DC promo
$objAD_NewCheckbox = New-Object System.Windows.Forms.Checkbox
$objAD_NewCheckbox.Location = New-Object System.Drawing.Size(10,110)
$objAD_NewCheckbox.Size = New-Object System.Drawing.Size(500,20)
$objAD_NewCheckbox.Text = "Install AD and DC promo"
$objAD_NewCheckbox.TabIndex = 6
$objForm.Controls.Add($objAD_NewCheckbox)
#This creates a label for the DomainMode TextBox1
$objLabel1 = New-Object System.Windows.Forms.Label
$objLabel1.Location = New-Object System.Drawing.Size(10,140)
$objLabel1.Size = New-Object System.Drawing.Size(280,20)
$objLabel1.Text = "Domain Mode"
$objForm.Controls.Add($objLabel1)
#This creates the DomainMode TextBox1
$objTextBox1 = New-Object System.Windows.Forms.TextBox
$objTextBox1.Location = New-Object System.Drawing.Size(10,160)
$objTextBox1.Size = New-Object System.Drawing.Size(100,20)
$objTextBox1.TabIndex = 0
$objForm.Controls.Add($objTextBox1)
#This creates the RUN button and sets the event
$RUNButton = New-Object System.Windows.Forms.Button
$RUNButton.Location = New-Object System.Drawing.Size(10,190)
$RUNButton.Size = New-Object System.Drawing.Size(75,23)
$RUNButton.Text = "RUN"
$RUNButton.Add_Click({$objForm.Close()})
$RUNButton.TabIndex = 9
$objForm.Controls.Add($RUNButton)
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
I think you have answered all your questions there.
In the other code you are referring to, the button has an event handler. Whatever is inside this code block, gets executed when you press the button.
Inside the code block, the code is looking for which checkbox has been checked using the if loop. All you need to do is call the script you want from the correct if loop. Instead of external script files, you could also call scriptblocks which I think is a cleaner way.
$handler_button1_Click=
{
$listBox1.Items.Clear();
if ($checkBox1.Checked) { "C:\MyScript\Script1.ps1" }
if ($checkBox2.Checked) { "C:\MyScript\Script2.ps1" }
if ($checkBox3.Checked) { "C:\MyScript\Script3.ps1" }
}
If you want to do more with the results of the script after execution, you can put that too inside the if block.
I have written one in GUI that uses checkboxes if you want to refer: Windows Patching Assistant

Powershell finding remote logged on user

I'm fairly new to Powershell and wrote this form for some colleagues. I just wanted to get some advice and guidance on how it's written, what could be better or if it's fine the way it is. Thanks.
enter image description here
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
function _Search {
if ($UernameSearch) {Clear-Variable -Name UernameSearch}
$OutputBox1.Clear()
$TextSearch = $SearchBox1.Text
$UernameSearch = gwmi win32_computersystem -comp $TextSearch | select USername
if ($UernameSearch) {
if ($UernameSearch.USername) {$OutputBox1.Text = $UernameSearch.USername}
else {$OutputBox1.Text = "No user currently logged on."}}
else {$OutputBox1.Text = "Is $TextSearch offline?"}
$OutputBox1.Enabled = $true
}
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Who's Logged In"
$Icon = [system.drawing.icon]::ExtractAssociatedIcon($PSHOME + "\powershell.exe")
$objForm.Icon = $Icon
$objForm.Size = New-Object System.Drawing.Size(250,200)
$objForm.StartPosition = "CenterScreen"
$objForm.MaximizeBox = $false
$objForm.FormBorderStyle = 'Fixed3D'
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") {$objForm.Close()}})
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(30,5)
$objLabel.AutoSize = $true
$objLabel.TextAlign = "TopCenter"
$objLabel.Text = "Use this tool to find who is currently
logged onto a remote machine."
$objForm.Controls.Add($objLabel)
$objLabe2 = New-Object System.Windows.Forms.Label
$objLabe2.Location = New-Object System.Drawing.Size(60,50)
$objLabe2.Size = New-Object System.Drawing.Size(150,15)
$objLabe2.Text = "Enter Computer Name"
$objForm.Controls.Add($objLabe2)
$SearchBox1 = New-Object System.Windows.Forms.TextBox
$SearchBox1.Location = New-Object System.Drawing.Size(15,70)
$SearchBox1.Height = 25
$SearchBox1.Width = 210
$SearchBox1.Multiline = $false
$SearchBox1.Add_KeyDown({if ($_.KeyCode -eq "Enter") {_Search}})
$objForm.Controls.Add($SearchBox1)
$SearchButton = New-Object System.Windows.Forms.Button
$SearchButton.Location = New-Object System.Drawing.Size(15,95)
$SearchButton.Height = 25
$SearchButton.Width = 210
$SearchButton.Text = "GO!"
$SearchButton.Add_Click({_Search})
$objForm.Controls.Add($SearchButton)
$OutputBox1 = New-Object System.Windows.Forms.TextBox
$OutputBox1.Location = New-Object System.Drawing.Size(15,125)
$OutputBox1.Multiline = $false
$OutputBox1.Height = 25
$OutputBox1.Width = 210
$OutputBox1.Multiline = $false
$OutputBox1.Enabled = $false
$objForm.Controls.Add($OutputBox1)
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
Windows.Forms vs WPF
Windows Presentation Foundation is the more advanced alternative. It's nice, but there's a learning curve.
A lot of the display code you have would vanish off into a XAML file (a blob of XML) meaning you can get on with the wiring behind.
Variable naming
Hungarian notation (the "obj" prefix) is a bit pointless. Especially considering that you don't apply it consistently.
Pascal case or camel case are popular conventions these days. e.g.
Pascal: MyVariable
Camel: myVariable
I have my own, most people do. Pick something you're comfortable with and use it consistently.
function _Search
It's not easy to discover nor is it reusable. Why the underscore?
Consider making a generalised function that returns this information as a collection of objects. Your GUI can consume the output from that function and display it.
Assembly.LoadWithPartialName
Obsolete. It's ambiguous at best. Besides, there are neater PowerShell alternatives:
Add-Type -Assembly System.Windows.Forms
Aliases
gwmi, select, truncated parameter names: None of these have a place in production code.
Aliaes saves you a few keystrokes and that's fine when you're tapping away at the console. When you're developing something to share they increase obscurity.
Anyone reviewing or updating your code in the future must be familiar with both the command, which at least is descriptive, and the alias.
Consistent formatting
Style is always personal, but there are a small number of very popular ways of writing branching statements like this snippet:
if ($UernameSearch) {
if ($UernameSearch.USername) {$OutputBox1.Text = $UernameSearch.USername}
else {$OutputBox1.Text = "No user currently logged on."}}
else {$OutputBox1.Text = "Is $TextSearch offline?"}
Consider the style I prefer:
if ($UsernameSearch) {
if ($UsernameSearch.Username) {
$OutputBox1.Text = $UsernameSearch.Username
} else {
$OutputBox1.Text = "No user currently logged on."
}
} else {
$OutputBox1.Text = "Is $TextSearch offline?"
}