How to Prompt for Input Using PowerShell GUI

This article shows how to create a GUI prompt for user input in PowerShell with 3 different examples. You may want to display a simple dialog to show Yes or No, a dialog showing multiple selectable options, or a dialog for the user to input strings.

Getting Simple Response

In this example, I will create a simple yes/no GUI input prompt.

[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null

$res = [System.Windows.Forms.MessageBox]::Show('Are you sure?' , "Confirm" , 4)
if ($res -eq 'Yes') {
    Write-Host 'Confirmed'
}
else
{
   Write-Host 'Not Confirmed'
}

Run:

Getting Multiple Options

PromptForChoise is a Dialog method of offering multiple selection options to users.

[string[]]$seasons = "Spring","Summer","Fall","Winter"
$res = $host.ui.PromptForChoice('Travel Planning', 'Choose By Season : ', $seasons, 0)
Write-Host $seasons[$res]

Run:

Getting Password Input from GUI Dialog

In this example, I will create a dialog asking user’s password. * will be displayed instead of showing the user’s typed characters in MaskedTextBox.

$form = New-Object System.Windows.Forms.Form

# Password Input
$password = New-Object Windows.Forms.MaskedTextBox
$password.Size = New-Object System.Drawing.Size(200,20)
$password.PasswordChar = '*'
$password.Top  = 50
$password.Left = 200
$form.Controls.Add($password)

# Title
$form.Text = 'Validate'
$form.Size = New-Object System.Drawing.Size(500,200)
$form.StartPosition = 'CenterScreen'
$form.AutoSize = $true

# OK Button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Size = New-Object System.Drawing.Size(100,30)
$OKButton.Top  = 100
$OKButton.Left = 250
$OKButton.Text = 'OK'
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$form.AcceptButton = $OKButton
$form.Controls.Add($OKButton)

# Text label 
$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(50,50)
$label.Size = New-Object System.Drawing.Size(200,20)
$label.Text = 'Enter Your Password :'
$form.Controls.Add($label)

# Show Form
$res = $form.ShowDialog()

if ($res -eq 'OK')
{
  Write-Host "Password Entered"

  # $password.Text can be used for validation logic
}

Run:

You may also be interested in the articles below:

How to Uninstall Application Remotely Using PowerShell

How to restore VM Snapshot remotely using PowerShell

Useful List of PowerShell Commands

How to download files from the Web using PowerShell

Leave a Comment