In the last few weeks, I have written a good number of PowerShell scripts that accept input from the user in the form of traditional prompt boxes (e.g. in one situation, I needed the user to enter Sql connection string to execute custom actions against a database). And it appeared to me it might be useful to share the function to produce a simple prompt box in PowerShell.

So without wasting much time, here’s the function:

 

{syntaxhighlighter brush: powershell;fontsize: 100; first-line: 1; }[System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”) | Out-Null;

function prompt ($caption, $text, $defaultValue) {
$prompt = New-Object “System.Windows.Forms.Form”;
$prompt.Width = 500;
$prompt.Height = 150;
$prompt.Text = $caption;
$prompt.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen;

$textLabel = New-Object “System.Windows.Forms.Label”;
$textLabel.Left = 50;
$textLabel.Top = 20;
$textLabel.Width = 400;
$textLabel.Text = $text;

$textBox = New-Object “System.Windows.Forms.TextBox”;
$textBox.Left = 50;
$textBox.Top = 50;
$textBox.Width = 400;

if ([String]::IsNullOrEmpty($defaultValue) -eq $false) {
$textBox.Text = $defaultValue;
}

$confirmation = New-Object “System.Windows.Forms.Button”;
$confirmation.Left = 350;
$confirmation.Top = 75;
$confirmation.Width = 100;
$confirmation.Text = “Ok”;

$eventHandler = [System.EventHandler]{$prompt.Close();};
$confirmation.Add_Click($eventHandler) ;

$prompt.Controls.Add($confirmation);
$prompt.Controls.Add($textLabel);
$prompt.Controls.Add($textBox);
$ret = $prompt.ShowDialog();

return $textBox.Text;
}{/syntaxhighlighter}

The first line of the above script loads the System.Windows.Forms assembly into your script session. Please note that apart from some core .Net assemblies, you need to manually load all other assemblies you need in your PowerShell scripts.

The rest is a simple script creating various UI components, stitching them together and showing them as a dialog. Here’s a sample invocation of the above function:

 

$server = prompt ('Server') ('Enter server name') ('(local)\SqlExpress');

The first argument is the title of the prompt dialog, the second is the descriptive label and the final one, an optional default value to shown in the textbox. If omitted, the textbox would show up as empty.

And here’s how the prompt dialog created by above sample invocation looks like:

Powershell Prompt Dialog