GUI for Powershell Scripts
PowerShell Windows

How To Create GUI For PowerShell Scripts – Detailed Instruction

Generally, Windows customers are using GUI every day without knowing much about it. If you are the same, this article is for you! Here we provide you more detailed information about this interesting application and its features. Then, we will walk you through steps on how to create GUI for PowerShell scripts in detail. Let’s scroll down to read! 

GUI And Its Features 

For IT experts, GUI is not new software. It is an abbreviation for the graphical user interface. 

GUI is also known as a system of visual factors applied to computer programs. In other words, this system displays objects and actions that are done by users to make a change in specific objects like the light, the color. 

So, how does a GUI work? The answer is it applies icons, menus, windows to get along with orders like moving, deleting files. Also, mouse and keyboards can be used with arrow keys and keyboard shortcuts. Below are common elements that use in GUI: 

  • Dialog box: A sort of window that presents additional information and requires users to input data. 
  • Button: A graphical expression on which when users press on, it will perform actions
  • Menu: A list of options or commands for users to choose from. 
  • Icon: A small sign that presents a program or a file. 
  • Menu bar: A narrow, horizontal bar that includes the menu labels 
  • Tab: An area that users can click on to process a command or to get into another area 
  • Window: A rectangular area of the computer displaying a program or software being opened. 
  • Toolbar: A buttons row that offers controlling functions 
  • Ribbon: A function that groups programs and activities 

How To Create GUI For PowerShell Scripts-Detailed Guide 

We all know that PowerShell is a modern automation tool for Windows that lets users apply a wide range of .NET framework objects. Especially if you use .NET API, you can easily make a simple GUI for your PowerShell Scripts. 

In this part, we will guide you to create PowerShell GUI focusing on elements like text boxes, labels, and many other powershell GUI examples. For easy editing, we will utilize PowerShell forms of 3.0 + and PowerShell ISE.

Create Windows Form With PowerShell

In the first step, you should use the class System.Windows. Form to create the forms. To download this unit, use the code: Add-Type -assembly System.Windows.Forms. 

Next, make the screen forms that consist of required elements by the next code: $main_form = New-Object System.Windows.Forms.Form. 

Then, create the title and set up the size of the Windows:

$main_form.Text =’GUI for my PoSh script’

$main_form.Width = 600

$main_form.Height = 400

If there is a default with the elements of the form, you can apply the AutoSize property option to adjust them to automatically stretch into the right form: 

$main_form.AutoSize = $true

Then, you can present the accomplished form on the screen:

$main_form.ShowDialog()

GUI for Powershell Scripts

Displaying the accomplished form on the screen 

Adding Dialog-Box Components To your PowerShell Form

The displayed form on the screen is still empty though. It is time for you to add other elements like graphical dialog and control using the following code lines: 

$Label = New-Object System.Windows.Forms.Label

$Label.Text = “AD users”

$Label.Location  = New-Object System.Drawing.Point(0,10)

$Label.AutoSize = $true

$main_form.Controls.Add($Label)

Be noted that add above lines behind this the code line: ($mai on_form.ShowDialog(). 

Then, make a drop-down list and write down the account lists from the Active Directory domain. We advise users to use Get-ADuser cmdlet to get the list:

$ComboBox = New-Object System.Windows.Forms.ComboBox

$ComboBox.Width = 300

$Users = get-aduser -filter * -Properties SamAccountName

Foreach ($User in $Users)

{

$ComboBox.Items.Add($User.SamAccountName);

}

$ComboBox.Location  = New-Object System.Drawing.Point(60,10)

$main_form.Controls.Add($ComboBox)

After that, you can add two additional labels to the form. The second line opens to users when a specific user account has its last password changed.  

$Label2 = New-Object System.Windows.Forms.Label

$Label2.Text = “Last Password Set:”

$Label2.Location  = New-Object System.Drawing.Point(0,40)

$Label2.AutoSize = $true

$main_form.Controls.Add($Label2)

$Label3 = New-Object System.Windows.Forms.Label

$Label3.Text = “”

$Label3.Location  = New-Object System.Drawing.Point(110,40)

$Label3.AutoSize = $true

$main_form.Controls.Add($Label3)

To put the button element on this form, follow the code lines: 

$Button = New-Object System.Windows.Forms.Button

$Button.Location = New-Object System.Drawing.Size(400,10)

$Button.Size = New-Object System.Drawing.Size(120,23)

$Button.Text = “Check”

$main_form.Controls.Add($Button)

In order to change the date from the TimeStamp format to another form, you should apply the function [datetime]::FromFileTime:

$Button.Add_Click(

{

$Label3.Text =  [datetime]::FromFileTime((Get-ADUser -identity $ComboBox.selectedItem -Properties pwdLastSet).pwdLastSet).ToString(‘MM dd yy : hh ss’)

}

)

In case, you don’t want all elements to expose on the screen, use the Visible function by following the code lines: 

$Label3.Text.Visible = $false

# or $True if you want to show it

Finally, run the PowerShell script to check. You will see a drop-down list full of user accounts from the AD. Select a random account to check, you can get the last time it changed the password.  

GUI for Powershell Scripts

Check the PowerShell scripts 

Using Standard Windows Dialog Box Components In PowerShell Scripts

The question is how to use the dialog box element in PowerShell scripts? This will require a PowerShell Gui builder to have some change in writing coding lines. Let’s have a look at them in detail: 

Present to message box: 

There are many factors and requirements in this element such as the button, the title, the icon, and others. Simply, to expose message with Ok, users can use the following lines:   

[void] [System.Windows.MessageBox]::Show( “All changes have been implemented successfully “, “Script completed”, “OK”, “Information” ).

– In case, user want the message box to appear by a required answer, write the code lines: 

$answer = [System.Windows.MessageBox]::Show( “Do you want to remove this user?”, ” Removal Confirmation”, “YesNoCancel”, “Warning” ). 

– To get the credentials: 

$creds = Get-Credential $UserName

$getUsername = $creds.GetNetworkCredential( ).UserName

$getPassword = $creds.GetNetworkCredential( ).Password

– If users want to expose default Windows, choose the file dialog box with a file name filter: 

Add-Type -AssemblyName System.Windows.Forms

$initialDirectory = [Environment]::GetFolderPath(‘Desktop’)

$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog

$OpenFileDialog.InitialDirectory = $initialDirectory

$OpenFileDialog.Filter = ‘Script files (*.ps1;*.cmd;*.bat)|*.ps1;*.bat;*.cmd’

$OpenFileDialog.Multiselect = $false

$response = $OpenFileDialog.ShowDialog( ) # $response can return OK or Cancel

if ( $response -eq ‘OK’ ) { Write-Host ‘You selected the file:’ $OpenFileDialog.FileName }

GUI for Powershell Scripts

Choosing the file 

– To open the folder browse, follow the next command:

$shell = New-Object -ComObject Shell.Application

$selectedfolder = $shell.BrowseForFolder( 0, ‘Select a folder to proceed’, 16, $shell.NameSpace( 17 ).Self.Path ).Self.Path

GUI for Powershell Scripts

Opening the folder browse 

– Select the form of printer dialog: 

Add-Type -AssemblyName System.Windows.Forms

$prntdlg = New-Object System.Windows.Forms.PrintDialog

$prntdlg.AllowCurrentPage = $false

$prntdlg.AllowPrintToFile = $trur

$prntdlg.AllowSelection = $false

$prntdlg.AllowSomePages = $true

$prntdlg.ShowNetwork = $true

$response = $prntdlg.ShowDialog( )# $response can return OK or Cancel

if ( $response -eq ‘OK’ ) { Write-Host ‘Selected printer:’ $prntdlg.PrinterSettings.PrinterName }

GUI for Powershell Scripts

Selecting the form of the printer box 

– Users also can use another program to express the GUI as the Out-GridView. It will allow users to present graphical tables with filled information easily. For example, the below coding lines can help pinpoint the running services: 

$Svcs = Get-Service | Where-Object {$_.Status -EQ “Running”}| Out-GridView -Title “List of running services” -PassThru| Select -ExpandProperty Name

GUI for Powershell Scripts

Pinpointing the running service

Building PowerShell Scripts’ GUI Using Visual Studio

Windows Presentation Foundation (WPF) is suggested for you as a PowerShell GUI builder. It helps users to make visual interfaces on Windows applications. You can download this program in the 2019 version. To launch this software, follow our below steps: 

– Create a new project while running the Microsoft Visual Studio by following the link File > New > Project. Then, choose Visual C# > Windows Forms App (.NET Framework). 

GUI for Powershell Scripts

Creating a new project 

– Place the control element with dragging and dropping options: 

GUI for Powershell Scripts

Using the element in the left toolbox panel 

– The XAML code will be created, and you have to save it into the file C:\PS\Script\MainWindow.xaml. Remember to open this file by applying Notepad. Then, delete the following string: x:Class=”test.MainWindow”. Next, save the changes with the XAML code. 

– To download the XAML objects, users will have to use the following code lines:

$XamlPath = “C:\PS\Script\MainWindow.xaml”

[xml]$Global:xmlWPF = Get-Content -Path $XamlPath

try{

Add-Type -AssemblyName PresentationCore,PresentationFramework,WindowsBase,system.windows.forms

} catch {

Throw “Failed to load WPF.”

}

$Global:xamGUI = [Windows.Markup.XamlReader]::Load((new-object System.Xml.XmlNodeReader $xmlWPF))

$xmlWPF.SelectNodes(“//*[@*[contains(translate(name(.),’n’,’N’),’Name’)]]”) | %{

Set-Variable -Name ($_.Name) -Value $xamGUI.FindName($_.Name) -Scope Global

}

– You can use the code line: $xamGUI.ShowDialog() to expose the form. 

Use the Online Editor To Create a Form For Your PoSh Script

Our last suggestion today is using an online editor to design graphical elements for PowerShell forms such as https://poshgui.com.

GUI for Powershell Scripts

Using an online tool to make GUI. 

With this online tool, you should copy the code (as the picture below) into the Visual Studio Code with the extension of PowerShell. Then, change their name before running the code. 

GUI for Powershell Scripts

Copying the code into Visual Studio Code 

The Bottom Line!

It is interesting to adjust elements within the Windows operating system. And we must say that creating GUI for PowerShell scripts is not easy work. To do it, users ought to have a basic knowledge of coding and programming. However, we hope this article was helpful to you. If you still have any questions, don’t hesitate to head back to us with a message. Have a great time reading! 

Maybe you are interested in

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top