The default command-line interface of PowerShell script makes them difficult to use for non-technical users. You can add a simple graphical user interface (GUI) to your PowerShell scripts to make them user-friendly and to allow to perform specific tasks that require user interaction.
Frameworks to add GUI to PowerShell scripts
To add a GUI to PowerShell scripts, there are two most commonly used frameworks:
- .NET Windows Forms class (WinForms) — to create a GUI form, it is necessary to describe all the graphical elements and their properties in the script code. Then add script logic into the PowerShell code. This method is ideal for beginners and simple GUI scripts.
- Use standard Windows graphical dialogs which only allows the user to be informed and asked to make a choice.
- Windows Presentation Framework (WPF). WPF allows to quickly create a GUI form with the necessary controls in a graphical editor and export the form to an XML-based format. The appearance and logic of the script is divided into two files.
Create a GUI for PowerShell Script Using the WinForms Class
Let’s use the WinForms class to create a simple PowerShell script, which shows the last password change date for an AD user.
The overall process of creating a GUI PowerShell script using .NET Windows Forms is as follows:
- Create a PS1 script and load the Windows Forms assembly.
- Create a graphical dialog form (System.Windows.Forms.Form), set its title, size, and position.
- Add graphical controls to the form (labels, buttons, checkboxes, etc). Set their size, appearance, text, position.
- Add event handlers to control elements events (for example, a handler for a button event).
- Add a menu bar to the form (optional).
- Show the form to the user.
Start by creating a new .PS1 file (you can use the built-in PowerShell ISE, or install VSCode, or even Notepad++ as a PowerShell code editor).
Create GUI Form with PowerShell
Load the .NET System.Windows.Forms assembly:
Add-Type -assembly System.Windows.Forms
Then create a form object. The form is essentially a blank canvas for the placement of graphical elements.
$main_form = New-Object System.Windows.Forms.Form
Set the form title, width, and height (in pixels):
$main_form.Text ='GUI for my PowerShell script' $main_form.Width = 600 $main_form.Height = 400
Now display the form on the screen:
$main_form.ShowDialog()
Run the script (press F5 in your code editor).
Add Control Items to a PowerShell Form
ow add individual interface elements to the form. The following graphical elements can be added to a form:
- Label (show a text)
- TextBox (used to get user input)
- Button
- CheckBox
- RadioButton
- ComboBox (drop down list)
- ChekedListBox
- GroupBox
- ListBox
- DataGridView
- ListView
- TreeView
- DateTimePicker
- PictureBox
- ProgressBar
- HScrollBar
- VScrollBar
- ContextMenu (right-click menu)
- Menu (top menu)
Let’s add a Label element that displays a custom text.
$Label = New-Object System.Windows.Forms.Label $Label.Text = "AD users" # Set font family name and size $Label. Font = 'Microsoft Sans Serif,14' # Set element position based on pixels from left and top of form $Label.Location = New-Object System.Drawing.Point(0,10) $Label.AutoSize = $true $main_form.Controls.Add($Label)
Then add a ComboBox item to a form. This is a drop-down list control that contains the list of AD users (generated by using the Get-ADuser cmdlet from the PowerShell Active Directory module).
$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)
Add two more labels:
- Label2 with a static text.
- Label3 will show the last password change date for the selected AD user.
$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)
Now add the control Button object:
$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" # Set button background and font colors (optional) # Button. BackColor = "#45fc03" # Button. ForeColor = "#ffffff" $main_form.Controls.Add($Button)
Insert the element code before the ShowDialog method. Run the script to see how your GUI form looks like.
Add Event Handlers to PowerShell Script
After the creation of a form with a graphical element, add some logic to the script. We will add a handler to the button click event:
$Button.Add_Click(
{
$Label3.Text = [datetime]::FromFileTime((Get-ADUser -identity $ComboBox.selectedItem -Properties pwdLastSet).pwdLastSet).ToString('MM dd yy : hh ss')
}
)
In this case, the script gets the value of the pwdLastSet attribute of an AD user selected in the $ComboBox.
Add Custom Menu GUI in PowerShell Scripts
Then you can add a top menu to the form created earlier. For example, my menu will contain the following items:
- File
- — Save
- — Exit
- Help
- — About
The following WinForms objects are used to create the menu:
- MenuStrip – add a horizontal menu;
- ToolStripMenuItem – add menu item;
- ToolStripButton – bind action to menu item.
Create some new objects for your menu:
$menuMain = New-Object System.Windows.Forms.MenuStrip $mainToolStrip = New-Object System.Windows.Forms.ToolStrip $menuFile = New-Object System.Windows.Forms.ToolStripMenuItem $menuSave = New-Object System.Windows.Forms.ToolStripMenuItem $menuExit = New-Object System.Windows.Forms.ToolStripMenuItem $menuHelp = New-Object System.Windows.Forms.ToolStripMenuItem $menuAbout = New-Object System.Windows.Forms.ToolStripMenuItem $toolStripOpen = New-Object System.Windows.Forms.ToolStripButton $toolStripSave = New-Object System.Windows.Forms.ToolStripButton $toolStripExit = New-Object System.Windows.Forms.ToolStripButton $toolStripAbout = New-Object System.Windows.Forms.ToolStripButton
Insert your menu to the GUI form ($main_form):
$main_form.MainMenuStrip = $menuMain $main_form.Controls.Add($menuMain) [void]$mainForm.Controls.Add($mainToolStrip)
Show the first menu item:
# Show Menu Bar [void]$main_Form.Controls.Add($menuMain) # Menu: File $menuFile.Text = "File" [void]$menuMain.Items.Add($menuFile)
Then add a drop-down menu item to the File menu:
# Menu: File -> Save
$menuSave.Text = "Save"
$menuSave.Add_Click({SaveFile})
[void]$menuFile.DropDownItems.Add($menuSave)
# Menu: File -> Exit
The Add_Click method used to perform an action when the user clicks a menu item (in this example, the script was stopped when the Exit menu was clicked):
$menuExit.Text = "Exit"
$menuExit.Add_Click({$main_Form.Close()})
[void]$menuFile.DropDownItems.Add($menuExit)
Now add the next menu section:
# Menu: Help
$menuHelp.Text = "Help"
[void]$menuMain.Items.Add($menuHelp)
# Menu: Help -> About
$menuAbout.Text = "About"
$menuAbout.Add_Click({ShowAbout})
[void]$menuHelp.DropDownItems.Add($menuAbout)
Run the PowerShell script. A horizontal menu with nested sub-menu items will be displayed at the top of the form.
Add the handlers for the Click event on the rest menu items (SaveFile, OpenFile, ShowAbout). Let’s define the following PowerShell function for the About menu:
function ShowAbout {
[void] [System.Windows.Forms.MessageBox]::Show( “My simple PowerShell GUI script with dialog elements and menus v1.0”, “About script”, “OK”, “Information” )
}
Save your PowerShell script to the PS1 file. To run the PowerShell script, users can use the command:
powershell.exe -ExecutionPolicy Bypass -NoProfile -WindowStyle Hidden -File "C:\ps\posh_gui.ps1"
Or you can save this command in a BAT-file. Users can then run the .bat file to start the PowerShell script, regardless of the execution policy settings.
Hint. Or convert your PS1 script file into EXE app using the PS2EXE module:
Install-Module ps2exe -Repository PSGallery ps2exe -inputFile “C:\PS\posh_gui.ps1” -outputFile “C:\PS\posh_gui.exe”
Using Standard Windows Dialog Boxes in PowerShell Scripts
In cases where you only need to display some popup messages or get user input, you can use the standard Windows graphical dialogs in scripts.
To display a simple modal window with text and buttons, use the MessageBox class.
Show an message box with text and OK button:
[void] [System.Windows.MessageBox]::Show( "All changes have been implemented successfully ", "Script completed", "OK", "Information" )
Display a message box that requires a response (Yes/No/Cancel):
$answer = [System.Windows.MessageBox]::Show( "Dou you want to remove this user?", " Removal Confirmation", "YesNoCancel", "Warning" )
Prompt a user for credentials and split it on two variables:
$creds = Get-Credential $UserName $getUsername = $creds.GetNetworkCredential( ).UserName $getPassword = $creds.GetNetworkCredential( ).Password
Building the GUI for PowerShell Scripts with Visual Studio
Then you need to create a complex GUI form with a large number of control element, use the Visual Studio with a Windows Presentation Foundation (WPF) as a simple GUI builder.
Download and install the Visual Studio Community 2022 > select .Net desktop development.
Run the Microsoft Visual Studio and create a new Project (File > New > Project). Select Visual C# > WPF App (.NET Framework) C#.
Use the Windows Forms element in the left Toolbox pane to place your control element on the form (with drag&drop).
Visual Studio generates an Extensible Application Markup Language (XAML) that contains the GUI form settings. Save this code into the file C:\PS\Script\MainWindow.xaml. Open this file using Notepad and remove the string:
x:Class="test.MainWindow”
Now you can read this XAML code from your PowerShell script and display a Windows Form.
Load the WPF assembly:
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName System.Windows.Forms
[xml]$XAML = Get-Content "C:\ps\gui\mainwindow.xaml"
$XAML.Window.RemoveAttribute('x:Class')
$XAML.Window.RemoveAttribute('mc:Ignorable')
$XAMLReader = New-Object System.Xml.XmlNodeReader $XAML
$MainWindow = [Windows.Markup.XamlReader]::Load($XAMLReader)
$XAML.SelectNodes("//*[@Name]") | %{Set-Variable -Name ($_.Name) -Value $MainWindow.FindName($_.Name)}
Show the form:
$xamGUI.ShowDialog()
Add event handlers for contol elements
Now add some event handlers for contol elements. For example, I want a message to appear when I click OK button.
- In the XAML file, set a name for the OK button, for example:
Name="OkButton"
- Add logic to your PowerShell script:
# Define the event handler function OnOkButtonClick { $null = [System.Windows.MessageBox]::Show("Button OK clicked!") } # Add the event handler to the "OK" button $OkButton = $MainWindow.FindName("OkButton") $OkButton.Add_Click({ OnOkButtonClick }) # Show the window $MainWindow.ShowDialog() | Out-Null
Check that the action from the OnOkButtonClick function is now performed when a button is clicked on the form.







7 comments
I have the following script which a Sharepoint page from powershell. I want other users to access it outside the server by proving parameter as required. Is GUI Powershell the best way to do it?
Good morning
Firstly can I just say thank you for this post as a complete beginner to this it has been immensely useful and allowed me to create all of my menus for the relatively simple tasks i was looking to do.
I have however tun into what seems in my mind to be a simple thing yet search after search has not revealed an answer for me. I have created a menu in Visual Studio that on the click of a button launches a second menu. The second menu contains a list of buttons that when clicked I want them to launch a pre-written power shell script. What I am failing to find is the command I need to add to teh On-Click function of the button that will launch a Powers hell script by clicking it ?
Excellent and very useful.
But i have a question:
Post adding the components and once form is ready.. can we convert to .exe? All i need is, double click an icon from my desktop and see my form?
Please advise!
Yes. you can use ps2exe. it is pretty simple to use and will work on most powershellscripts.
you can use iexpress, that’s implemented in Windows
I get a blank form and execution seems to be halted.
EDIT: Figured it out, I copy/pasted the show main form command, not cut/pasted!
Hi Cyril,
Thanks for a fun startup GUI for running commands. I kept testing the pre-Visual Code examples, waiting for the part of the example that wouldn’t render, etc. and was pleasantly surprised that everything works. I quickly added ‘button grid’ for about 80 go to scripts, library of dialog messages and sub actions, and to avoid issues, have the buttons unclickable, until I use menu option to activate buttons to what I am working on).
I’m now converting the canned reports (i.e., status of backup jobs from Veeam that store HTML report on network, confirming services are running for core production applications across a dozen Windows server) to ps2exe executables and then it will be very sharable.
Next up will be create visual control status bar (to see entire server inventory at a glance, and alert on new processes, applications or services added to any server in inventory).