What's new
  • Donate
    TheWindowsForum.com needs donations to stay online!
    Love TheWindowsForum.com? Then help keep it alive by sending a donation!

Powershell - How to Create a GUI for your script

WELCOME TO THEWINDOWSFORUM COMMUNITY!

Our community has more than 50.000 registered members, and we'd love to have you as a member. Join us and take part in our unbiased discussions among people of all different backgrounds about Windows OS, Software, Hardware and more.

Buster Friendly

Well-Known Member
May 5, 2022
107
32
OS
Windows 10
BR
Chrome 102.0.5005.63

How to Create a GUI for PowerShell Scripts?​

MAY 20, 2022 CYRIL KARDASHEVSKYPOWERSHELL
When used by users (not sysadmins or programmers), one of the significant drawbacks of PowerShell scripts is its command-line interface. The result of the scripts is displayed in the PowerShell CLI console and it is not always convenient for the end-user. However, PowerShell is a powerful and modern automation tool for Windows that allows you transparently use a variety of .NET Framework objects. For example, using the .NET API, you can easily create a simple graphical interface (GUI) for your PowerShell scripts.

In this example, we’ll show how to create a simple Windows GUI form using PowerShell and place various standard .NET Windows Forms controls elements on it: textboxes, buttons, labels, checkboxes/listboxes, radiobuttons, datagrids, etc. For example, our task is to build a simple GUI for a PowerShell script that shows the last password change time for the Active Directory user. In this example, we use PowerShell 3.0+ and PowerShell ISE for easy code editing.

Create Windows Form with PowerShell​

To use the .NET functionality to create forms, we will use the class System.Windows.Forms. To load this class into a PowerShell session, you can use the following code:

Add-Type -assembly System.Windows.Forms
Now create the screen form (window) to contain elements:
$main_form = New-Object System.Windows.Forms.Form
Set the title and size of the window:
$main_form.Text ='GUI for my PoSh script'

$main_form.Width = 600

$main_form.Height = 400
If the elements on the form are out of window bounds, use the AutoSize property to make the form automatically stretch.
$main_form.AutoSize = $true
Now you can display the form on the screen.
$main_form.ShowDialog()
powershell gui


Adding Dialog-Box Components to Your PowerShell Form​

As you can see, an empty form is displayed. To add graphical dialog and control elements to it, add the code below before the last line ($main_form.ShowDialog()).
Create a label element on the form:
$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)
Create a drop-down list and fill it with a list of accounts from the Active Directory domain. You can get the AD user list using the Get-ADuser cmdlet (from Active Directory for Windows PowerShell 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 to the form. The second will show the time of the last password change for the selected user account:
$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 put the button on the form:
$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)
The following code will be executed when the user clicks on the button. To convert the date from the TimeStamp format to the more convenient form, we use 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')

}

)
If you want to hide some of the GUI elements on a Windows Form, use the Visible property. For instance:
$Label3.Text.Visible = $false

# or $True if you want to show it
Run the PowerShell script. As you can see, the drop-down list is automatically filled with the names of the user accounts from Active Directory. If you select the user account and click the Check button, the form displays the time when the user’s last password was changed in Active Directory.

powershell gui builder

So, you built your first simple graphical user interface for a PowerShell script. What’s next? Now you can add a more complex UI element to your PowerShell form.

Commonly Used PowerShell UI Elements​

Similarly, you can create the following graphic elements on the form:
  • CheckBox — used to list some options and select them before running script;
  • RadioButton — lists some text options and allows to select only one of them;
  • TextBox — user can write some text. It can be used to get the value of the PowerShell script parameter;
  • Label — used for labeling some parts of scripts’ GUI;
  • ChekedListBox — shows a list of items;
  • DataGridView — allows to view some tabular data;
  • GroupBox — allows viewing and grouping a set of controls together;
  • ListBox — can store several text items;
  • TabControl — allows you to split your form into different areas (tabs);
  • ListView — displays a list of items with text and (optionally) an icon;
  • TreeView — hierarchical objects view;
  • DateTimePicker — allows to select date and time;
  • TrackBar — scrollable control;
  • PictureBox — allows to show a picture on the form;
  • ProgressBar — indicates the operation progress;
  • HScrollBar — horizontal scroll bar;
  • VScrollBar — vertical scroll bar;
  • ContextMenu — right-click menus;
  • Menu — top menu in your form.

Using Standard Windows Dialog Box Components in PowerShell Scripts​

You can invoke some of the standard Windows graphical dialog boxes to inform the user and prompt him to make a choice. Let’s take a look at some of the standard graphics window calls in PowerShell.

Show MessageBox​

Message is a mandatory MessageBox attribute. Title, button, and icon are optional.
For example, to show a message box with OK only:
[void] [System.Windows.MessageBox]::Show( "All changes have been implemented successfully ", "Script completed", "OK", "Information" )
Show a message box with a mandatory answer required:
$answer = [System.Windows.MessageBox]::Show( "Dou you want to remove this user?", " Removal Confirmation", "YesNoCancel", "Warning" )
powershell gui examples


Prompt a user for credentials and split it on two variables:
$creds = Get-Credential $UserName

$getUsername = $creds.GetNetworkCredential( ).UserName

$getPassword = $creds.GetNetworkCredential( ).Password
powershell gui designer

Show default Windows select file dialog box with a filter by file names:
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 }
powershell ui

Open the Browse for folder dialog window:
$shell = New-Object -ComObject Shell.Application

$selectedfolder = $shell.BrowseForFolder( 0, 'Select a folder to proceed', 16, $shell.NameSpace( 17 ).Self.Path ).Self.Path
powershell menu gui

Select printer dialog form:
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 powershell


Another useful PowerShell command for presenting graphical information from a script to a user is Out-GridView. The Out-GridView cmdlet allows you to display any data (PowerShell object attributes) in the form of a graphical table, in which it can be filtered and sorted according to the desired criteria.
For example, the following script will list the running services on Windows. The user must select the desired services (several lines can be selected by holding the Ctrl key) and save the selection to a variable.
$Svcs = Get-Service | Where-Object {$_.Status -EQ "Running"}| Out-GridView -Title "List of running services" -PassThru| Select -ExpandProperty Name
powershell create gui

Now you can use the list of services selected by the user in the Out-GridView for further processing in your PowerShell script.
The -PassThru option is used to pass the selected objects in the table through the pipeline through the standard PowerShell pipe.
Hint. Other examples of using the Out-GridView cmdlet are described in the following articles:

Building Simple Menus with Sub-Menus for PowerShell GUI Script​

With the WinForms class, you can add complex hierarchical menus to your graphical PowerShell scripts. In this example, we will add a few menu items to a previously created PowerShell form with a simple structure:
  • File
  • Open
  • Save
  • Exit
  • Help
  • About
To create a horizontal menu on a Windows form, you need to create a MenuStrip object. Menu items use ToolStripMenuItem objects. ToolStripButton objects are needed to bind actions (PowerShell functions) to menu items.
Create some new WinForms 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

$menuOpen = 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
Now you need to bind your menu to the GUI form ($main_form):
$main_form.MainMenuStrip = $menuMain

$main_form.Controls.Add($menuMain)

[void]$mainForm.Controls.Add($mainToolStrip)
Now you can display the first menu:
# Show Menu Bar

[void]$main_Form.Controls.Add($menuMain)

# Menu: File

$menuFile.Text = "File"

[void]$menuMain.Items.Add($menuFile)
Then you need to add a dropdown items to the File menu:
# Menu: File -> Open

$menuOpen.Text = "Open"

$menuOpen.Add_Click({OpenFile})

[void]$menuFile.DropDownItems.Add($menuOpen)

# Menu: File -> Save

$menuSave.Text = "Save"

$menuSave.Add_Click({SaveFile})

[void]$menuFile.DropDownItems.Add($menuSave)

# Menu: File -> Exit
Using the Add_Click method, you can add an action when clicking on a menu item (in this example, clicking the menu will call a method to close the form and stop the PowerShell script):
$menuExit.Text = "Exit"

$menuExit.Add_Click({$main_Form.Close()})

[void]$menuFile.DropDownItems.Add($menuExit)
Now you can 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. As you can see, a horizontal menu with nested submenu items has appeared at the top of the form.
powershell gui example

In the code for some menu items, we have added handlers for the Click event on the menu item: SaveFile, OpenFile, ShowAbout. Now you have to define these functions that will be called when the menu items are clicked.

For example, we will add a PowerShell function ShowAbout:
function ShowAbout {

[void] [System.Windows.MessageBox]::Show( "My simple PowerShell GUI script with dialog elements and menus v1.0", "About script", "OK", "Information" )

}
powershell graphical interface

Building PowerShell Scripts’ GUI Using Visual Studio​

You can use Visual Studio with a WPF (Windows Presentation Foundation) as a simple PowerShell GUI builder. Download and install Visual Studio Community 2019 version.
WPF is a part of the .NET Framework that can be used to visualize user interfaces in Windows apps.
Run Microsoft Visual Studio and create a new Project (File > New > Project). Select Visual C# > Windows Forms App (.NET Framework)
powershell gui creator

Use the Windows Forms element in the left Toolbox pane to place your control element on the form (with drag&drop).
powershell script gui


The Visual Studio will generate a XAML code for you. Save this code into the file C:\PS\Script\MainWindow.xaml. Open this file using Notepad and remove the following string:
x:Class="test.MainWindow”
And save the changes in the XAML file.
Now you can read this XAML code from your PowerShell script and display a Windows Form.
Use the following function to load the XAML object:
$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

}
To display your form use:
$xamGUI.ShowDialog()

Use the Online Editor to Create a Form for Your PoSh Script​

For more convenient creation of graphical elements for PowerShell forms, you can use the online editor to create a GUI form for PowerShell scripts: https://poshgui.com/ (is no longer free). With it, you can create a beautiful form with the necessary graphical dialog elements.
gui for powershell

Create a Windows form with a simple GUI designer and get the ready PoSh code for your GUI scripts. Just copy this code into your PowerShell ISE or Visual Studio Code with PowerShell extension, change element names (optionally), and run the code to display the generated form on your computer.

powershell gui editor



source: The IT.BROS
 

Buster Friendly

Well-Known Member
May 5, 2022
107
32
OS
Windows 10
BR
Chrome 102.0.5005.63
Well done! :)
it's not from me, I found that nice piece of work. I was quite happy to find this... once, when I need it, I'm happy to use it, but first, it will be a "TRY to use it" :D
 

Buster Friendly

Well-Known Member
May 5, 2022
107
32
OS
Windows 10
BR
Chrome 102.0.5005.115
it works pretty awesome.

I created a lil tool to de-re-activate some services (The Windows Update Problem) and it really rocks!

IT WORKS!!!!

Im totally happy!
 

Online statistics

Members online
4
Guests online
45
Total visitors
49
Top