Create a Text Box to Accept User Input for PowerShell GUI

Do you have a PowerShell GUI that needs to accept text input? Maybe you want to be able to copy and paste a list of computers, ip addresses, user names or some other data. I will show you how to add a text box into your PowerShell GUI to handle that input. If you haven’t created a PowerShell GUI yet but are interested in doing so, check out my previous post on how to make a simple GUI.


Code

Let’s start breaking down the sections of code needed to make this happen. I like to put the input box code inside of a function, but you may decide you don’t want to do that. To see the entire code, look at my GitHub.

The first thing we need to do is create the form via the .NET windows forms namespace. Here we specify the text that we want in the title of the window, as well as what size we want it to be. Some optional settings are to have the window start in the center of the screen, preventing resize of the window and putting the window on top of other open windows.

    ### Creating the form with the Windows forms namespace
    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.Drawing
    $form = New-Object System.Windows.Forms.Form
    $form.Text = 'Enter the appropriate information' ### Text to be displayed in the title
    $form.Size = New-Object System.Drawing.Size(310,625) ### Size of the window
    $form.StartPosition = 'CenterScreen'  ### Optional - specifies where the window should start
    $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedToolWindow  ### Optional - prevents resize of the window
    $form.Topmost = $true  ### Optional - Opens on top of other windows

Next, we will add an OK button to the bottom of the window. Once the data has been inputted, the user will hit the OK button to pass the input into the next step of the GUI.

    ### Adding an OK button to the text box window
    $OKButton = New-Object System.Windows.Forms.Button
    $OKButton.Location = New-Object System.Drawing.Point(155,550) ### Location of where the button will be
    $OKButton.Size = New-Object System.Drawing.Size(75,23) ### Size of the button
    $OKButton.Text = 'OK' ### Text inside the button
    $OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
    $form.AcceptButton = $OKButton
    $form.Controls.Add($OKButton)

Then we will add a cancel button in case the user decides against running the GUI.

    ### Adding a Cancel button to the text box window
    $CancelButton = New-Object System.Windows.Forms.Button
    $CancelButton.Location = New-Object System.Drawing.Point(70,550) ### Location of where the button will be
    $CancelButton.Size = New-Object System.Drawing.Size(75,23) ### Size of the button
    $CancelButton.Text = 'Cancel' ### Text inside the button
    $CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
    $form.CancelButton = $CancelButton
    $form.Controls.Add($CancelButton)

In order to avoid confusion and help the user understand what type of data to input, we are going to add a label. This label will be defined by the parameter used when the function is called. If you want to hard code the label text, just replace the $Input_Type with the text that you want displayed.

    ### Putting a label above the text box
    $label = New-Object System.Windows.Forms.Label
    $label.Location = New-Object System.Drawing.Point(10,10) ### Location of where the label will be
    $label.AutoSize = $True
    $Font = New-Object System.Drawing.Font("Arial",12,[System.Drawing.FontStyle]::Bold) ### Formatting text for the label
    $label.Font = $Font
    $label.Text = $Input_Type ### Text of label, defined by the parameter that was used when the function is called
    $label.ForeColor = 'Red' ### Color of the label text
    $form.Controls.Add($label)

The last piece of the GUI window is the text box that will be used to accept inputted text.

    ### Inserting the text box that will accept input
    $textBox = New-Object System.Windows.Forms.TextBox
    $textBox.Location = New-Object System.Drawing.Point(10,40) ### Location of the text box
    $textBox.Size = New-Object System.Drawing.Size(275,500) ### Size of the text box
    $textBox.Multiline = $true ### Allows multiple lines of data
    $textbox.AcceptsReturn = $true ### By hitting enter it creates a new line
    $textBox.ScrollBars = "Vertical" ### Allows for a vertical scroll bar if the list of text is too big for the window
    $form.Controls.Add($textBox)

Putting together the finishing touches so that it all works together and cleans up the inputted data.

    $form.Add_Shown({$textBox.Select()}) ### Activates the form and sets the focus on it
    $result = $form.ShowDialog() ### Displays the form 

    ### If the OK button is selected do the following
    if ($result -eq [System.Windows.Forms.DialogResult]::OK)
    {
        ### Removing all the spaces and extra lines
        $x = $textBox.Lines | Where{$_} | ForEach{ $_.Trim() }
        ### Putting the array together
        $array = @()
        ### Putting each entry into array as individual objects
        $array = $x -split "`r`n"
        ### Sending back the results while taking out empty objects
        Return $array | Where-Object {$_ -ne ''}
    }

    ### If the cancel button is selected do the following
    if ($result -eq [System.Windows.Forms.DialogResult]::Cancel)
    {
        Write-Host "User Canceled" -BackgroundColor Red -ForegroundColor White
        Write-Host "Press any key to exit..."
        $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
        Exit
    }

Calling the Text Box

Now that the code to create the GUI text box is finished, we need to call the text box and return the inputted data. I will share a few examples of how to utilize the text box we just created. The below examples are assuming that you’ve put the text box inside of a function with the use of a parameter.

Function GUI_TextBox ($Input_Type){...}

Here is an example of how to use the text box to accept a list of computer names. This example will just output the list of computer names inputted to screen. In order to make this useful, you will need to add your code to have the script take action on those computer names. Maybe you need to conduct power actions on a list of computers or any number of admin actions.

###############################################################################
### Computer Name(s) example of how to utilize the GUI_TextBox function
###############################################################################
$Computers = GUI_TextBox "Computer Names(s):" ### Calls the text box function with a parameter and puts returned input in variable
$Computer_Count = $Computers | Measure-Object | % {$_.Count} ### Measures how many objects were inputted

If ($Computer_Count -eq 0){ ### If the count returns 0 it will throw and error
    Write-Host "Nothing was inputed..." -BackgroundColor Red -ForegroundColor White
    Return
}
Else { ### If there was actual data returned in the input, the script will continue
    Write-Host "Number of computers entered:" $Computer_Count -BackgroundColor Cyan -ForegroundColor Black
    $Computers
    ### Here is where you would put your specific code to take action on those computers inputted
}

Here is an example of how to use the text box to accept a list of users. This example will just output the list of users inputted to screen. In order to make this useful you will need to add your code to have the script take action on those user. Maybe you need to disable their Active Directory accounts or any number of admin actions.

###############################################################################
### User Name(s) example of how to utilize the GUI_TextBox function
###############################################################################
$Users = GUI_TextBox "User Names(s):" ### Calls the text box function with a parameter and puts returned input in variable
$User_Count = $Users | Measure-Object | % {$_.Count} ### Measures how many objects were inputted

If ($User_Count -eq 0){ ### If the count returns 0 it will throw and error
    Write-Host "Nothing was inputed..." -BackgroundColor Red -ForegroundColor White
    Return
}
Else { ### If there was actual data returned in the input, the script will continue
    Write-Host "Number of users entered:" $User_Count -BackgroundColor Cyan -ForegroundColor Black
    $Users
    ### Here is where you would put your specific code to take action on those users inputted
}

Text Box in Action

When you are done, you should have something that looks like this:

That’s it for now, thanks for reading!


Check out my other blog posts:

Media Sync: Organize Your Photos and Videos with PowerShell

Do you have photos and videos that you have taken over the years that are scattered all over the place? Do you want to have all your photos and videos organized? Do you want all your photos and videos to have a standardized naming scheme? If you answered YES to these questions, then this is…

NetNeighbor Watch: The PowerShell Alternative To Arpwatch

In this post, we are going to setup NetNeighbor Watch on a Raspberry Pi. NetNeighbor Watch can keep an eye on your network and send you an email when a new host is discovered. NetNeighbor Watch is done completely in PowerShell. The results are very similar to those of arpwatch. NetNeighbor Watch is for anyone…

Generate a Citrix Desktop Report Based on Active Directory Users

In this post, we are going to merge data from two different sources to generate a report that can provide insight into your Citrix environment. I will show you how to combine Active Directory data for the users in your domain with Citrix data. This report will provide you with the following knowledge: Users that…

Creating a PowerShell Module to Improve Your Code

Do you have PowerShell code that you reuse in your scripts over and over? Do you have server names hard coded in variables? Are you using a text file or CSV file to import server names? Do you find yourself only utilizing one server out of a cluster of servers to make your PowerShell commands?…

Generate a DHCP Report Via PowerShell

Today we are going to look at how to generate a DHCP scope statistics HTML report by using PowerShell. This report will give you one location to see all of your DHCP scope statistics across all of your Windows DHCP servers. It will dynamically pull the DHCP servers and associated DHCP scopes within your Active…

Increase VMware VM Disk Size with PowerShell

In this post, I will cover how to use PowerShell to increase the disk size of a Windows 10 VM running in a VMware vCenter environment. Automating simple but time consuming tasks like this can save precious time for your support staff or yourself. There are two parts to accomplishing this task; first we need…

Manage Citrix Tags with PowerShell

In this post, we are going to cover how to manage Citrix tags with PowerShell. Citrix Studio is a great tool, but it can be very time consuming especially if you have to do bulk tag actions. Citrix tags can be used in several methods, but this post is focused on desktop tagging. This post…

Utilizing PowerShell Out-GridView as a GUI Alternative

In my previous post, I showed how you can build a simple menu driven PowerShell GUI; check it out here. To further improve upon that simple GUI, we will go over how to use Out-GridView. Out-GridView is a built-in powershell cmdlet that sends the output from a given command to an interactive window. This post…

How to Create a Simple PowerShell GUI

Have you ever wanted to create a menu driven PowerShell GUI to conduct a series of automated tasks? You are in luck, because that is exactly what we are going to cover in this post. This very simple PowerShell GUI will help you easily distribute your code to other team members or maybe you just…

2 thoughts on “Create a Text Box to Accept User Input for PowerShell GUI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s