How to create a GUI for PowerShell scripts?
When used by users (not system administrators or developers), one of the major drawbacks of PowerShell scripts is their command-line interface. The output of the scripts is displayed in the PowerShell CLI console and is not always convenient for the end user. However, PowerShell is a powerful and modern automation tool for Windows that enables you to seamlessly 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 will show how to create a simple Windows GUI form using PowerShell and place various elements of standard Windows Forms controls in it: text boxes, buttons, labels, check boxes / list boxes, radio buttons, grids. data, etc. For example, our task is to create a simple GUI for a PowerShell script that displays the time of the last password change for the Active Directory user. In this example, we use PowerShell 3.0+ and PowerShell ISE to make code editing easier.Create Windows Form with PowerShell
To use the .NET functionality to create forms, we will use the System.Windows.Forms class. To load this class in 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 window title and size:
$main_form.Text = "GUI for my PoSh script"
$main_form.Width = 600
$main_form.Height = 400
If the form elements are outside the bounds of the window, use the AutoSize property to make the form stretch automatically.
$main_form.AutoSize = $true
Now you can display the form on the screen.
$main_form.ShowDialog ()
Add dialog box components to your PowerShell form
As you can see, an empty form is displayed. To add multiple graphical dialogs and control elements to it, add the following code 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 populate it with a list of accounts from the Active Directory domain. You can get the list of AD users by using the Get-ADuser cmdlet (from the Active Directory Module for Windows PowerShell):
$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 tags 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 the button. To convert the date from the TimeStamp format to the most convenient format, we use the [datetime] :: FromFileTime function:
$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 example:
$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 populated with the names of the Active Directory user accounts. If you select the user account and click Check , the form displays the time the user's last password was changed in Active Directory.So you created your first simple GUI for a PowerShell script. Whats 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 the script;
- RadioButton: lists some text options and allows you to select only one of them;
- TextBox: user can type text. It can be used to get the value of the PoSh script parameter;
- Label: used to label some parts of the GUI of scripts;
- ChekedListBox: shows a list of items;
- DataGridView: allows you to see some tabular data;
- GroupBox: allows you to view and group a set of controls;
- ListBox: can store multiple text items;
- TabControl: allows you to divide your form into different areas (tabs);
- ListView: displays a list of items with text and (optionally) an icon;
- TreeView - hierarchical object view;
- DateTimePicker: allows you to select the date and time;
- TrackBar - scrollable control;
- PictureBox: allows to display an image on the form;
- ProgressBar: indicates the progress of the operation;
- HScrollBar: horizontal scroll bar;
- VScrollBar: vertical scroll bar;
- ContextMenu: context menus;
- Menu - top menu on 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 ask them to choose. Let's take a look at some of the standard graphics window calls in PowerShell.
Show message box:
Message is a required attribute of MessageBox. The title, button, and icon are optional.
For example, to display a message box with just OK:
[void][System.Windows.MessageBox]::Show ("All changes have been implemented successfully", "Script completed", "OK", "Information")
Show a message box with a required response required:
$answer = [System.Windows.MessageBox]::Show ("Dou you want to remove this user?", "Removal Confirmation", "YesNoCancel", "Warning")
Prompt a user for credentials and split it into two variables:
$creds = Get-Credential $UserName
$getUsername = $creds.GetNetworkCredential().UserName
$getPassword = $creds.GetNetworkCredential().Password
Show Default Windows File Selection Dialog with a filter by filename: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}
$shell = New-Object -ComObject Shell.Application
$selectedfolder = $shell.BrowseForFolder (0, 'Select a folder to proceed', 16, $shell.NameSpace(17).Self.Path).Self.Path
Select Printer Dialog Form:Add-Type -AssemblyName System.Windows.Forms
$prntdlg = New-Object System.Windows.Forms.PrintDialog
$prntdlg.AllowCurrentPage = $false
$prntdlg.AllowPrintToFile = $true
$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}
Another PowerShell command useful for presenting graphical information from a script to a user is Out-GridView . The Out-GridView cmdlet allows you to display it as a graphical table, in which it can be filtered and sorted based on the desired criteria.
For example, the following script will list the services running on Windows. The user must select the desired services (multiple lines can be selected by holding down the Ctrl key) and save the selection in a variable.
$Svcs = Get-Service | Where-Object {$_.Status -EQ "Running"} | Out-GridView -Title "List of running services" -PassThru | Select -ExpandProperty Name
You can now use the list of user-selected services in Out-GridView for further processing in your PowerShell script.Create the PowerShell Scripts GUI with Visual Studio
You can use Visual Studio with WPF (Windows Presentation Foundation) as a simple PowerShell GUI generator. Download and install the 2019 version of Visual Studio Community.
WPF is part of the .NET Framework that can be used to display user interfaces in Windows applications.
Run Microsoft Visual Studio and create a new project (File> New> Project). Select Visual C #> Windows Forms Application (.NET Framework)
Use the Windows Forms element in the left toolbox panel to place your control element on the form (with drag and drop).
Visual Studio will generate a XAML code for you. Save this code in the C: PS Script MainWindow.xaml file. Open this file with Notepad and delete the following string:
x:Class = "test.MainWindow”
And save the changes to 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:PSScriptMainWindow.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/ (no longer free). With it, you can create a beautiful shape with the necessary dialogue elements.
And get the PoSh code ready for your GUI scripts. Just copy this code to your PowerShell ISE or Visual Studio Code with the PowerShell extension, change the names of the elements (optionally), and run the code to display the generated form on your computer.
Post a Comment