PowerShell offers one "native" way to gather input from a user: The Read-Host cmdlet. This command accepts a prompt, and allows the user to type their response. The response is placed into the pipeline. By adding the -AsSecureString switch, you cause the input to be hidden, and to be converted to a .NET secure string when going into the pipeline - perfect for passwords.
Read-Host is one of the few cmdlets whose behavior differs depending on where you use it. Each PowerShell host application - like the ISE, the console, and so forth - determines how it'll implement the cmdlet. So, in the console, a colon is added to the end of your prompt and the whole thing is displayed at the command-line, where the user types their response. In the more GUI-oriented ISE, Read-Host pops up a dialog box with a text box for the user's input, and a couple of buttons (Ok and Cancel).
A big question in class is often, "how can I
have a graphical dialog appear?" The easy answer is to go "underneath" PowerShell and use the .NET Framework. Its Visual Basic support includes an InputBox function, which is pretty easy to use from within the shell.
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$computer = [Microsoft.VisualBasic.Interaction]::InputBox("Enter a computer name", "Computer", "$env:computername")
The first line loads the necessary part of the .NET Framework into memory. That loading normally generates a success message, which I'm piping to Out-Null to suppress it. The next line actually launches the InputBox, which is a static method of the Visual Basic Interaction class. The method accepts three parameters, in this order:
- Your prompt. Nothing will be added to it, so format it however you like. Add a backtick-N (`n) inside double quotes to add a carriage return/line feed.
- The title for the dialog box, shown in its window title bar.
- A default value. Here, I'm retrieving the computername environment variable as a default.
You can omit the title and default if you want, or you can just omit the default value if you don't want to supply one. In this example, $computer will contain a specific value if the user presses the Cancel button in the dialog - I'll let you play with it to see what that "Cancel" value is :).
You can use the same trick to display a non-input dialog box, using the static MsgBox() method of the Interaction class. The docs for that are located here
, if you're interested.
[Quick reminder: We're getting down to the wire on the super-early-bird pricing for my June 2011 PowerShell class
. Check it out if you're interested in five days of the best PowerShell training on the planet.]
[Quick reminder, the sequel: My new PowerShell book has released additional chapters for your review, and the 50% discount has been extended. Get the details, then get the book