How to Build a PowerShell Form Menu for your PowerShell Scripts

choubertsprojects

The Best WordPress plugins!

1. WP Reset

2. WP 301 Redirects

3. WP Force SSL

PowerShell scripts are becoming more and more popular for the IT world. In order to get a better understanding of what your script does, it can be advantageous if you have some kind of menu in front that allows users to navigate through different parts of the script. Here is an example on how I built my own PowerShell form menu from scratch using Microsoft’s Form Designer toolkit:

The “powershell gui script” is an important part of any PowerShell project. This article will show you how to build a PowerShell Form Menu for your PowerShell Scripts.

How to Build a PowerShell Form Menu for your PowerShell Scripts

It’s time for another weekend project, and today you’ll learn how to create a lightweight system tray PowerShell form menu where you can quickly and conveniently execute your favorite PowerShell scripts. The final product may be seen below.

Using a system tray menu icon to run PowerShell scriptsUsing a system tray menu icon to run PowerShell scripts

By breaking down the procedure step by step, you’ll learn how to create your own PowerShell menu GUI in this post.

Requirements for the Environment and Knowledge

Please make sure you satisfy the following basic criteria before diving in:

The good news is that you won’t require Visual Studio, PoshGUI, or any other UI development tool for this project since the key components that this project will depend on are:

  • NotifyIcon — This is the customized system tray icon with which the user may interact.
  • ContextMenu — A container for the context menu that appears when the user right-clicks on the tray icon.
  • MenuItem — Each item in the right-click menu has its own object.

Let’s get started by opening your preferred PowerShell script editor.

You will create three functions for this project: two to show/hide the console for a nicer user experience, and one to add things to your systray menu. As you will see later in this essay, these features will serve as a basis for further usage to make your life much simpler.

Display/Hide the Console Window

When you run a PowerShell script, the familiar PowerShell console appears unless it is hidden. You should make sure the console isn’t up since the menu items in the PowerShell form you’ll construct will run scripts. All you want is for it to work.

You may use a little.NET to control whether the PowerShell console window appears or not when a script is run.

First, in the current session, add the Window.NET type. As you’ll see below, you’ll need to utilize some C# to do this. GetConsoleWindow and ShowWindow are the two methods that must be loaded into context. You may utilize these DLLs in the context of your PowerShell script by loading them into memory and exposing particular elements of the API:

#Insert dlls into the current console session’s context. Add-Type -Name Window -Namespace Console -MemberDefinition ‘Add-Type -Name Window -Namespace Console -MemberDefinition ‘ [DllImport(“Kernel32.dll”)] [DllImport(“user32.dll”)] public static extern IntPtr GetConsoleWindow(); ShowWindow(IntPtr hWnd, Int32 nCmdShow); public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);

As seen below, use the GetConsoleWindow() and ShowWindow() methods to create two functions utilizing the loaded above.

Start-ShowConsole is a function. $PSConsole = [Console.Window]::GetConsoleWindow() [Console.Window]::ShowWindow($PSConsole, 5) $PSConsole = [Console.Window]::ShowWindow($PSConsole, 5) Start-HideConsole is a function. $PSConsole = [Console.Window]::GetConsoleWindow() [Console.Window]::ShowWindow($PSConsole, 0) $PSConsole = [Console.Window]::ShowWindow($PSConsole, 0)

You’ve now built a mechanism to display and hide the console window at will using these two functions.

Note: You may utilize PowerShell transcripts or other text-based logging tools to observe output from scripts performed using the menu. This gives you more power than if you just ran the PowerShell session with the WindowStyle argument set to conceal.

By executing Start-HideConsole, you may now start writing script code. This prevents the PowerShell console window from appearing when the PowerShell form menu-driven script runs.

<# Initialization of functions and objects loading into memory Display a text-based loading bar or Write-Progress to the host #> Start-HideConsole <# Code to display your form/systray icon This will hold the console here until closed #>

It’s now time to make the menu choices. Generate a new function named New-MenuItem to ensure that you can simply create new choices in the future. When you use this method, a new MenuItem.NET object is created, which you may subsequently add to the menu.

Each menu selection will either start a new script or close the launcher. The New-MenuItem method provides three arguments to allow this functionality:

  • Text – This is the label that the user will click.
  • MyScriptPath – The location of the PowerShell script you want to run.
  • ExitOnly — This is the only way to get out of the launcher.

In the menu script, add the function snippet below.

param([string]) function New-MenuItem $MyScriptPath, [switch] $Text = “Placeholder Text” $ExitOnly = $false)))))))))))))))))))

Create a MenuItem object by assigning it to a variable as part of the New-MenuItem function.

#Initialization $MenuItem = New-Object System.Windows.Forms; $MenuItem = New-Object System.Windows.Forms; $MenuItem = MenuItem

After that, give the menu item a text label.

$MenuItem.Text = $Text if($Text) $MenuItem.Text = $Text if($Text) if($Text) if($Text) if($Text) if

Now add a MyScriptPath custom attribute to the MenuItem. When the item in the menu is clicked, this route will be invoked.

#Add logic to the click event if($MyScriptPath -and! $ExitOnly) $MenuItem | Add-Member -Name MyScriptPath -Value $MenuItem | Add-Member -Name MyScriptPath -Value $MenuItem | Add-Member -MemberType NoteProperty $MyScriptPath

To start the specified script, add a click event to the MenuItem. Start-Process offers a simple method to perform this inside a try/catch block, ensuring that any failures encountered when starting the script (such as PowerShell not being accessible or the script not existing at the specified path) are caught in your catch block.

$MenuItem.Add_Click({ try{ $MyScriptPath = $This.MyScriptPath #Used to find proper path during click event if(Test-Path $MyScriptPath){ Start-Process -FilePath “C:WindowsSystem32WindowsPowerShellv1.0powershell.exe” -ArgumentList “-NoProfile -NoLogo -ExecutionPolicy Bypass -File `”$MyScriptPath`”” -ErrorAction Stop } else { throw “Could not find at path: $MyScriptPath” } } catch { $Text = $This.Text [System.Windows.Forms.MessageBox]::Show(“Failed to launch $Text`n`n$_”) > $null } })

Sdd the rest of the code to provide the launcher an exit condition, then return your freshly formed MenuItem to be assigned to another variable during runtime.

If ($ExitOnly -and! ), provide a means to leave the launcher. $MenuItem) $MyScriptPath) $Form.Close.Add Click(); $Form.Close(); $Form.Close(); $For () Stop-Process #Handle any stuck processes ) $PID ) $PID ) $PID ) $PID ) $ #Please return our new MenuItem to us. $MenuItem is a menu item.

The New-MenuItem method should now be available! This is how the final function should look:

param([string]) function New-MenuItem $MyScriptPath, [switch] $Text = “Placeholder Text” $ExitOnly = $false))))))))))))))))))) #Initialization $MenuItem = New-Object System.Windows.Forms; $MenuItem = New-Object System.Windows.Forms; $MenuItem = MenuItem #Apply desired text if($Text){ $MenuItem.Text = $Text } #Add logic to the click event if($MyScriptPath -and! $ExitOnly) $MenuItem | Add-Member -Name MyScriptPath -Value $MenuItem | Add-Member -Name MyScriptPath -Value $MenuItem | Add-Member -MemberType NoteProperty $MyScriptPath } $MenuItem.Add_Click({ try{ $MyScriptPath = $This.MyScriptPath #Used to find proper path during click event if(Test-Path $MyScriptPath){ Start-Process -FilePath “C:WindowsSystem32WindowsPowerShellv1.0powershell.exe” -ArgumentList “-NoProfile -NoLogo -ExecutionPolicy Bypass -File `”$MyScriptPath`”” -ErrorAction Stop } else { throw “Could not find at path: $MyScriptPath” } } catch { $Text = $This.Text [System.Windows.Forms.MessageBox]::Show(“Failed to launch $Text`n`n$_”) > $null } }) If ($ExitOnly -and! ), provide a means to leave the launcher. $MenuItem) $MyScriptPath) $Form.Close.Add Click(); $Form.Close(); $Form.Close(); $For () Stop-Process #Handle any stuck processes ) $PID ) $PID ) $PID ) $PID ) $ #Please return our new MenuItem to us. $MenuItem is a menu item.

Copy and paste the preceding code into your PowerShell console and execute the function with some fictitious parameter values to test the New-MenuItem function. A.NET MenuItem object is returned, as you can see.

PS51> (New-MenuItem -Text “Test” -MyScriptPath “C:test.ps1”).GetType() IsPublic IsSerial Name BaseType ——– ——– —- ——– True False MenuItem System.Windows.Forms.Menu

How to Make a Launcher Form

Do you want more helpful hints like this? Visit https://nkasco.com/FriendsOfATA for my personal PowerShell blog.

It’s time to construct a system tray launcher that will show the menu now that you can quickly add new menu items.

Make a simple form object to which you may add components. This doesn’t have to be fancy since it will be hidden from the end user and will also keep the console operating in the background.

#Make a container for our components by creating a form. $Form denotes the New-Object System. Windows. Forms.Form Configure our form so that it is hidden. $Form. $Form.TransparencyKey = “Magenta” $Form.BackColor = “Magenta” $Form.BackColor = “Magenta” $Form.BackColor = “Magenta” $Form.BackColor = “Magenta” $Form.BackColor = “Magenta” $Form.BackColor = “Magenta” $Form $false ShowInTaskbar $Form. “None” for FormBorderStyle

Create the icon that will appear in the system tray next. I’ve opted to utilize the PowerShell icon in the example below. The code below generates a system tray icon at runtime. By adjusting the SystrayIcon variable to your preferred icon, you may change this symbol to your taste.

Check check the System’s documentation. To view different ways for loading an icon into memory, look at the Drawing.Icon class.

#Initialize and setup all required components. New-Object System.Windows.Forms.NotifyIcon $SystrayLauncher $SystrayIcon = [System.Drawing.Icon]::ExtractAssociatedIcon; $SystrayIcon = [System.Drawing.Icon]::ExtractAssociatedIcon; $Systray (“C:windowssystem32WindowsPowerShellv1.0powershell.exe”) $SystrayLauncher.Icon = $SystrayIcon; $SystrayIcon; $SystrayIcon; $SystrayIcon; $ $SystrayLauncher.Visible = $true $SystrayLauncher.Text = “PowerShell Launcher” $SystrayLauncher.Text = “PowerShell Launcher” $SystrayLauncher.Text = “PowerShell Launcher”

When the script is completed, a PowerShell icon should appear in your system tray, as seen below.

Now, using a new ContextMenu object, construct a container for your menu items and all of your menu items. The menu will include two scripts to execute and an exit option in this example.

$New-Object System $ContextMenu = New-Object System $ContextMenu = New-Object System $ContextM Windows. Forms. ContextMenu $LoggedOnUser = New-MenuItem -Text “Get Logged On User” -MyScriptPath “C:scriptsGetLoggedOn.ps1” $LoggedOnUser = New-MenuItem -Text “Get Logged On User” -MyScriptPath “C:scriptsGetLoggedOn.ps1” $RestartRemoteComputer = New-MenuItem -Text “Restart Remote PC” -MyScriptPath “C:scriptsrestartpc.ps1” $RestartRemoteComputer = New-MenuItem -Text “Restart Remote PC” -MyScriptPath “C:scriptsrestartpc.ps1” $ExitLauncher = New-MenuItem -Text “Exit” -ExitOnly $ExitLauncher = New-MenuItem -Text “Exit” -ExitOnly $ExitLauncher =

Next, add all of the newly formed menu items to the context menu. Each menu item will appear in the form context menu as a result of this.

#Insert menu items into the context menu. $ContextMenu. MenuItems. AddRange($LoggedOnUser) $ContextMenu. MenuItems. AddRange($RestartRemoteComputer) $ContextMenu.MenuItems. AddRange($ExitLauncher) #Add components to $SystrayLauncher’s form. $$$$$$$$$$$$$$$$

Activate the Launcher Form

Now that the form is ready, the next step is to display it while preventing the PowerShell console window from appearing. To avoid a stalled powershell.exe process, use Start-HideConsole, display the launcher form, and then show the console again with Start-ShowConsole.

#Launch Start-HideConsole $Form.ShowDialog() > $null Start-ShowConsole

Do you want more helpful hints like this? Visit https://nkasco.com/FriendsOfATA for my personal PowerShell blog.

You may get the whole code here: https://github.com/nkasco/PSSystrayLauncher

Your Recommendations

Congratulations for completing this assignment! You learnt the following in this article:

  1. How to make Windows API components visible.
  2. How to use WinForms to create context menus and add more menu items.
  3. In PowerShell, learn how to create a system tray icon.

This project should provide you with enough knowledge and expertise to construct your own PowerShell systray menu!

The “powershell gui generator” is a tool that allows users to build menus for their PowerShell scripts. The menu can be used in the script or as a standalone application.

Frequently Asked Questions

How do you create a menu in PowerShell?

A: Place a menu bar above the screen and then add items to it, or create individual menus in code.

How do I create a PowerShell script GUI?

A: You can use PowerShells GUI to create a script. This is an accessible feature with the command prompt or PowerShell itself.

Is there a GUI for PowerShell?

A: A GUI is not present in PowerShell, but there are multiple GUIs that one can use to create scripts and work with the tool. They are called Integrated Scripting Environment (ISE) which provides a graphical user interface for creating and running scripts without having to learn how to write any code or commands

Related Tags

  • powershell gui templates
  • free powershell gui builder
  • powershell gui examples
  • powershell gui builder open source
  • powershell gui menu bar

Table of Content