Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.

If you own the book already, login here to get free, online, searchable access to the entire book's content.

If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".

13.11 Program: Add a Console UI to Your Script

When you want to create a script that visualizes complex information for the user or supports advanced user interaction, sometimes you need this interface to work over remote connections or a web interface like Azure Cloud Shell.

This isn’t possible with graphical libraries such as WinForms, but as Figure 13-3 shows, console UIs handle this quite well. Also, sometimes you just need a good dose of nostalgia!

As a solution to this, you can use the Terminal.Gui library included as part of the Microsoft.PowerShell.ConsoleGuiTools module. Once you install this module, you can use the types and methods from the Terminal.Gui library to create as simple or complex UIs as you need. Example 13-12 demonstrates this in action.

wps4 1303
Figure 13-3. A console interface running in Azure Cloud Shell
Example 13-12. Show-ConsoleHelloWorld.ps1
#requires -Module Microsoft.PowerShell.ConsoleGuiTools
using namespace Terminal.Gui

## Load the required assemblies
$guiTools = (Get-Module Microsoft.PowerShell.ConsoleGuiTools -List).ModuleBase
Add-Type -Path (Join-path $guiTools Terminal.Gui.dll)

## Initialize our application
[Application]::Init()

## Create a window with a label and a button
$window = [Window] @{
    Title = 'Hello Window Title!'
    Height = 20
    Width = 50
}

$label = [Label] @{
    X = [Pos]::Center(); Y = [Pos]::Center() - 1
    Width = 11
    Text = 'Hello World'
}
$window.Add($label)

$button = [Button] @{
    X = [Pos]::Center(); Y = [Pos]::Center() + 1
    Text = 'OK'
}
$window.Add($button)

## Console windows doesn't have any features that let applications close
## by default (like Alt+F4 does on a Windows Forms application),
## so associate this with the "OK" button.
$button.add_Clicked({ [Application]::RequestStop() })

## Add the window to the application and run it.
[Application]::Top.Add($window)
[Application]::Run()

## Our script gets here once the user clicks the "OK" button
[Application]::Shutdown()

For more information about running scripts, see Recipe 1.2. For more information about installing modules, see Recipe 1.29.

See Also

Recipe 1.2, “Run Programs, Scripts, and Existing Tools”

Recipe 1.29, “Find and Install Additional PowerShell Scripts and Modules”