PowerShell User Interaction

20 Apr 2018
 

With a lot of scripts, automating repetitive tasks is the goal, and therefore user interaction should be minimal. That being said, PowerShell is rich in ways to handle it.

Pauses

For PowerShell 3 and up you can just do Pause to pause until the user presses enter.

Press Enter to continue...: _

For earlier versions, you could define a ‘Pause’ function with Read-Host:

function Pause {
    Read-Host "Press Enter to continue..." | Out-Null
}

Fall back to using cmd.exe:

function Pause {
    cmd /c "pause"
}

I’ve also seen people write pause functions to continue on any key press (not just enter) like this:

function Pause {
    Write-Host "Press any key to continue..."
    do {
        $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp")
    } while (9, 16, 17, 18, 91, 92, 144 -contains $x.VirtualKeyCode)
    # ignore some keys (Tab, Shift, Ctrl, Alt, WinL, WinR, NumLock) sent by certain events when running via RDP
}

Prompt for Choice

Another common way of getting user interaction is presenting a list of options using $host.UI.PromptForChoice.

$title = "Version number"
$message = "Is $version the correct version number?"

$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Use version number $version."
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Enter a version number manually."

$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

$result = $host.ui.PromptForChoice($title, $message, $options, 0)

switch ($result)
    {
        0 {
            Write-Host "Yes!"
        }
        1 {
            Write-Host "No!"
        }
    }

This will give your user an interface that looks like:

Version number
Is <someVersionNumber> the correct version number?
[Y] Yes  [N] No  [?] Help (default is "Y"):

They can then enter y for yes, n for no etc.

GUIs

If you’re using Windows PowerShell you also have the option for user interaction through GUIs. The cmdlet Out-GridView lets you visually filter or select objects, I’ve previously written a post specifically on Out-GridView. Having access to full .NET also allows you to easily create bespoke GUIs using Windows Forms or WPF, I’ve also previously written a post on this.