How to display GUI Message Boxes in PowerShell

By FoxLearn 11/18/2024 6:46:34 AM   114
In PowerShell, you can display a message box using the .NET Framework.

Many people see PowerShell as just a command line tool limited to text output. However, it's actually built on the .NET framework, allowing it to perform much more similar to what VB.NET or C# developers can achieve.

How to show a message box with a title and a message?

There are several ways to create GUIs in PowerShell, primarily using Windows Forms (WinForms) or Windows Presentation Foundation (WPF) for more complex tools.

However, for simpler tasks like displaying messages or gathering basic input a quick solution is to use [System.Windows.Forms.MessageBox], which requires just a single line of code instead of building full forms and controls.

The MessageBox class in the System.Windows.Forms namespace offers a versatile way to create a PowerShell message box. For instance, in its simplest form, you can use the Show() method to display a simple message in a PowerShell message box.

The System.Windows.Forms namespace isn't available by default in PowerShell. To create a powershell message box, you need to add the System.Windows.Forms assembly to your PowerShell by using the Add-Type cmdlet as shown below.

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show("Your message here", "Your title here")

Once this is done, we can now use the MessageBox class.

The MessageBox class has a key method called Show, which can be customized with various parameters to alter its behavior.

For example:

If you want to show a message that says "Hello, World !" with the title "Message", you would write:

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show("Hello, World !", "Message")

You can also customize the buttons and icons displayed in the message box.

For example:

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show("Do you want to continue?", "Message", [System.Windows.Forms.MessageBoxButtons]::YesNo, [System.Windows.Forms.MessageBoxIcon]::Question)

This example shows a message box with "Yes" and "No" buttons and a question mark icon. You can adjust the text and options as needed.