How to Build a PowerShell GUI for your Scripts

choubertsprojects

The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

PowerShell is a scripting language designed for system administration. It’s one of the most popular languages for this purpose, but there isn’t any GUI to do anything with it besides typing commands into a command line window. Here’s how to build your own PowerShell GUI using Visual Studio 2017 that will allow you to manage multiple servers at once and provide alerts when something goes wrong on them in real time.

The “powershell gui generator” is a tool that can be used to create a graphical user interface for your PowerShell scripts. It will generate the GUI and code necessary to create a GUI in the form of a PowerShell script.

How to Build a PowerShell GUI for your Scripts

Although PowerShell is a command-line tool, did you realize it can also be used to create graphical user interfaces? Sometimes a command-line interface isn’t the greatest choice for a certain situation. A good example is creating a PowerShell GUI for your support desk. This is one of those occasions when creating graphical tools is more suited.

Are you not a reader? Take a look at this related video.

Stop submitting helpdesk tickets. With Specops’ Safe Service Desk, you can expedite user password resets and unlocks: no helpdesk calls, a secure procedure, and pleased end-users. Try it for free right now!

PowerShell can make use of and expose.NET capabilities and capability. As a consequence, GUI front ends for the programs you design are feasible. Building PowerShell GUIs may be intimidating, particularly for beginners.

However, if you have any expertise with PowerShell scripting, there’s no reason why you shouldn’t learn and apply the technique of developing a graphical user interface for your scripts.

In this tutorial, you’ll learn how to use the Windows Presentation Framework to develop a PowerShell GUI (WPF).

Prerequisites

Please make sure you satisfy the following conditions before diving in:

  1. Visual Studio 2017 or newer is required. You’ll use this to construct a WPF-based graphical user interface. A free/community version is available for download.
  2. Visual Studio Code is my script editor of preference, but you may use whatever text editor you choose. Notepad++ and the built-in PowerShell ISE are two more possibilities.
  3. A machine running Windows 10 with Windows PowerShell 5.1 installed.

Script Development

You’ll write a simple script called Main.ps1 in this tutorial. You’ll create code in the script to query the Win32 LogicalDisk WMI class to get disk information from a local or distant machine.

To wrap a GUI around, you’ll need a script first. I went with a script that lets you specify a machine name and get disk information. This is not, by any means, required to create a GUI. Adapt your GUIs to your own scripts using the concepts you’ve learned in this lesson.

I’ll write a function that does the following tasks as an example script:

  1. Accept input for the computer to query’s name.
  2. Query the computer and save the information from the fixed disks to a variable.
  3. Please return the findings.

The Function is Being Written

Get-FixedDisk is the function you’ll need for this project, and it’s properly called. The goal of this project is to get information on the target machine’s non-removable or permanent disks.

While you may use this code as is, developing a GUI would be useful if you simply want to run a short query without having to dot source the function and manually type in the instructions every time.

Function Get-FixedDisk { [CmdletBinding()] # This param() block indicates the start of parameters declaration param ( <# This parameter accepts the name of the target computer. It is also set to mandatory so that the function does not execute without specifying the value. #> [Parameter(Mandatory)] [string]$Computer ) <# WMI query command which gets the list of all logical disks and saves the results to a variable named $DiskInfo #> $DiskInfo = Get-WmiObject Win32_LogicalDisk -ComputerName $Computer -Filter ‘DriveType=3’ $DiskInfo }

I’ve added a param() block to the code, as you can see. This tells the function to accept inputs depending on the data type specified.

I’ve included a Computer parameter in the example that takes a string value. It also assures that the function does not execute if the Computer argument is not given at runtime by adding the Mandatory parameter property.

The actual WMI query statement is seen on line 18, which receives a list of all logical disks and stores the results to a variable called $DiskInfo. I’ve also included a filter to obtain just the DriveType=3 disks. Only information on local fixed drives is shown with this filter.

Bringing the Code in (Dot Sourcing)

You now have a functional script and are ready to put it to the test. However, you must first import the code into a PowerShell session before you can try the script. Dot sourcing is a method of loading code into a PowerShell session.

Type a dot (.) and a space before the script path to dot source it. You may dot source the script if it was in the C:PoshGUI-sample folder, as seen below.

PS C:PoshGUI-sample> . .Main.ps1

If you’re not in the current working directory, you may also give the complete path. The complete path of the script is shown in the sample code below.

PS C:>. C:PoshGUI-sampleMain.ps1

We can now test the function we’ve constructed now that the code has been loaded into memory. The Get-FixedDisk function is used to query the machine poshLabExc in the example below.

PS51> Get-FixedDisk -Computer poshLabExc DeviceID : C: DriveType : 3 ProviderName : FreeSpace : 53037772800 Size : 135838822400 VolumeName : Windows DeviceID : D: DriveType : 3 ProviderName : FreeSpace : 14872641536 Size : 17178750976 VolumeName : Temporary Storage DeviceID : E: DriveType : 3 ProviderName : FreeSpace : 488202240 Size : 524283904 VolumeName : System Reserved

Creating the PowerShell graphical user interface

At this point, you’ve built the Main.ps1 script file, as well as the Get-FixedDisk function inside it. You might also test and check the function’s functionality.

You may start developing the GUI now that you know the script works.

Creating the GUI Form for PowerShell

First, think about how you want the GUI to appear and what components you want to employ. Our user interface will look like this for this basic example:

  • a text area where you may type in the computer’s name
  • a button that performs the action
  • a text box in which the findings may be shown

After that, you may start constructing it!

Open Visual Studio and create a new project to begin working on the GUI.

Once Visual Studio is open, click on File (1) –> New (2) –> Project (3).

Making a new project in Visual StudioMaking a new project in Visual Studio

Choose Visual C# (1), WPF App (.NET Framework) (2), change the name to PoshGUI-sample (3), then click OK in the New Project box.

Making a decision on a Visual Studio projectMaking a decision on a Visual Studio project

After the project has been created, a blank form with the name MainWindow.xaml will be shown.

MainWindow.xaml in Visual StudioMainWindow.xaml in Visual Studio

You must now format this form to meet our specifications. The controls and format that you’ll need to add are listed below.

  • Window
    • Disk Information is the title of the document.
    • 326 cm tall
    • 403 x 403 x 403 x 403 x 403
  • Constraints (4)
    • Label
      • “Computer Name:” is the content.
      • 10-10-10-10-10-10-10-10-10-10-10-10-10-10-10-10-10-10-10-10-10-10-10
    • TextBox
      • txtComputer is the name of the program.
      • Text: “”
      • 23 inches tall
      • 174 x 174 x 174 x 174 x 174
    • Button
      • btnQuery is the name of the button.
      • Query as content
      • 0 13, 12 0 0 0 0 0 0 0 0 0
    • TextBox
      • txtResults is the name of the file.
      • Text: “”
      • True if IsReadOnly is true.
      • 10/60/0/0/0/0/0/0/0/0/0/0/0
      • 225 cm tall
      • 373 x 373 x 373 x 373 x 373

The form’s ultimate look should resemble that seen in the figure below. You have the option of changing the layout of your window. Be inventive!

GUI Template for PowerShellGUI Template for PowerShell

Using the PowerShell GUI and the Script

You may now begin merging your design with the script whenever you’re satisfied with it.

PowerShell does not have the ability to show forms natively. At show the form, we must add a piece of code to the very top of our script that supports WPF Form rendering.

Add-Type PresentationFramework -AssemblyName

Then add code to do the following tasks:

  1. Import and read the form’s XAML code.
  2. Create variables that are dynamically allocated to each designated control.
  3. Showcase the form

The modified code for your script is shown below.

Note: Be careful to change the $xamlFile line to link to the entire location of your MainWindow.xaml file.

Add-Type PresentationFramework -AssemblyName Function Get-FixedDisk { [CmdletBinding()] # This param() block indicates the start of parameters declaration param ( <# This parameter accepts the name of the target computer. It is also set to mandatory so that the function does not execute without specifying the value. #> [Parameter(Mandatory)] [string]$Computer ) <# WMI query command which gets the list of all logical disks and saves the results to a variable named $DiskInfo #> $DiskInfo = Get-WmiObject Win32_LogicalDisk -ComputerName $Computer -Filter ‘DriveType=3’ $DiskInfo } # where is the XAML file? $xamlFile = “C:PoshGUI-sampleMainWindow.xaml” #create window $inputXML = Get-Content $xamlFile -Raw $inputXML = $inputXML -replace ‘mc:Ignorable=”d”‘, ” -replace “x:N”, ‘N’ -replace ‘^<Win.*’, ‘<Window’ [XML]$XAML = $inputXML #Read XAML $reader = (New-Object System.Xml.XmlNodeReader $xaml) try { $window = [Windows.Markup.XamlReader]::Load( $reader ) } catch { Write-Warning $_.Exception throw } # Create variables based on form control names. # Variable will be named as ‘var_<control name>’ $xaml.SelectNodes(“//*[@Name]”) | ForEach-Object { #”trying item $($_.Name)” try { Set-Variable -Name “var_$($_.Name)” -Value $window.FindName($_.Name) -ErrorAction Stop } catch { throw } } Get-Variable var_* $Null = $window.ShowDialog()

It’s worth noting that $Null Equals $window. The final piece of code in your script must always be ShowDialog().

You should see the sample output below when you execute this code by running the Main.ps1 script.

Variable and field mappings in the PowerShell GUIVariable and field mappings in the PowerShell GUI

As you can see, the variables for the three mentioned controls have been allocated. When we add the control logic code later in the script, these variable names will be referenced.

  • var btnQuery
  • var btnComputer
  • var txtResults

Bear in mind that the script at this point can only Showcase the form, but the controls are useless since you haven’t added the code yet.

The Button Click Event Code is Added

Begin adding the code to the controls to get and show the disk information data now that you’ve successfully adjusted the script to import and display the GUI.

Only the btnQuery button will be given an action in this project. The remaining controls will only be used to control input and output/display. This implies that all btnQuery needs is a click event code.

To add the click action to btnQuery, assign the code below to its corresponding variable name $var btnQuery. Copy the code below and insert it in between the Get-Variable var_* and $Null = $window.ShowDialog() code references in the script.

$var btnQuery.Add_Click( { #clear the result box $var txtResults.Text = “” if ($result = Get-FixedDisk -Computer $var_txtComputer.Text) { foreach ($item in $result) { $var txtResults.Text = $var txtResults.Text + “DeviceID: $($item.DeviceID)`n” $var txtResults.Text = $var txtResults.Text + “VolumeName: $($item.VolumeName)`n” $var txtResults.Text = $var txtResults.Text + “FreeSpace: $($item.FreeSpace)`n” $var txtResults.Text = $var txtResults.Text + “Size: $($item.Size)`n`n” } } }) $var_txtComputer.Text = $env:COMPUTERNAME

Putting the Finished PowerShell GUI to the Test

With all of the pieces in place, here’s the finished code for our script, which includes the function as well as the PowerShell GUI we created.

Add-Type PresentationFramework -AssemblyName Function Get-FixedDisk { [CmdletBinding()] # This param() block indicates the start of parameters declaration param ( <# This parameter accepts the name of the target computer. It is also set to mandatory so that the function does not execute without specifying the value. #> [Parameter(Mandatory)] [string]$Computer ) <# WMI query command which gets the list of all logical disks and saves the results to a variable named $DiskInfo #> $DiskInfo = Get-WmiObject Win32_LogicalDisk -ComputerName $Computer -Filter ‘DriveType=3’ $DiskInfo } #where is the XAML file? $xamlFile = “C:UsersjunesourcereposPoshGUI-samplePoshGUI-sampleMainWindow.xaml” #create window $inputXML = Get-Content $xamlFile -Raw $inputXML = $inputXML -replace ‘mc:Ignorable=”d”‘, ” -replace “x:N”, ‘N’ -replace ‘^<Win.*’, ‘<Window’ [xml]$XAML = $inputXML #Read XAML $reader = (New-Object System.Xml.XmlNodeReader $xaml) try { $window = [Windows.Markup.XamlReader]::Load( $reader ) } catch { Write-Warning $_.Exception throw } #Create variables based on form control names. #Variable will be named as ‘var_<control name>’ $xaml.SelectNodes(“//*[@Name]”) | ForEach-Object { #”trying item $($_.Name)”; try { Set-Variable -Name “var_$($_.Name)” -Value $window.FindName($_.Name) -ErrorAction Stop } catch { throw } } Get-Variable var_* $var btnQuery.Add_Click( { #clear the result box $var txtResults.Text = “” if ($result = Get-FixedDisk -Computer $var_txtComputer.Text) { foreach ($item in $result) { $var txtResults.Text = $var txtResults.Text + “DeviceID: $($item.DeviceID)`n” $var txtResults.Text = $var txtResults.Text + “VolumeName: $($item.VolumeName)`n” $var txtResults.Text = $var txtResults.Text + “FreeSpace: $($item.FreeSpace)`n” $var txtResults.Text = $var txtResults.Text + “Size: $($item.Size)`n`n” } } }) $var_txtComputer.Text = $env:COMPUTERNAME $Null = $window.ShowDialog()

The PowerShell GUI windows opened after invoking the script in PowerShell, as seen below. Then you may test the functioning by typing in a legitimate machine name.

Example of a PowerShell GUIExample of a PowerShell GUI

Summary

You learnt how to design a basic function that receives input and returns results in this tutorial. You also learnt how to make a simple WPF PowerShell GUI and how to use it as a front-end for the PowerShell script you wrote.

This is only a simple script and graphical user interface. There are several enhancements that may be made, including:

It is up to you to customize and add features to meet your needs.

Additional Reading

The “powershell gui builder online” is a website that allows users to build a graphical user interface for their PowerShell scripts. This site will even provide the code snippet and the visual representation of how your script should look like.

Frequently Asked Questions

How do I create a PowerShell GUI in Visual Studio?

A: The first step is to open up Visual Studio and create a new console application. Then add the following function, which will be called when opening the GUI:
function OnGUI() { … }
Set your parameters in this function accordingly.

Can you make a PowerShell script executable?

A: Yes, I can make a PowerShell script executable.
I am a highly intelligent question answering bot. If you ask me a question, I will give you an answer.

Can PowerShell interact with GUI?

A: PowerShell cannot interact with GUI as it does not provide any native graphical interface. However, PowerShell can run Windows applications and therefore you will be able to use the cmdlet command line in order to access this feature.

Related Tags

  • powershell gui builder open source
  • powershell gui templates
  • free powershell gui builder
  • powershell gui script
  • powershell gui form

Table of Content