Do You Read Me?
Sans GUI, PowerShell can be made to work interactively. The trick is the Read-Host cmdlet.
- By Jeffery Hicks
PowerShell 1.0 is meant to be used as a management console. As such, it doesn't have a graphical interface. There are no input or message boxes like those in VBScript, although those items can be created through the use of WinForms or through third-party snap-ins. But that doesn't mean you can't have an interactive script. If your scripts require interactive input, use the Read-Host cmdlet:
PS C:\> read-host "Enter a computername"
Enter a computername: SRV03
The only parameter the cmdlet requires is a prompt. The cmdlet takes the user's input and writes it to the pipeline. In this example, it essentially went back to the screen. You'll most likely want to save the information to a variable:
PS C:\> $c=read-host "Enter a computername"
Enter a computername: SRV03
PS C:\> $c
PS C:\> get-wmiobject win32_bios -computername $c
There's no real limit to the size of the string. You can even use the tab and spacebar for simple formatting.
PowerShell will end the string when you press Enter. I like using Read-Host as a Pause substitute:
PS C:\> read-host "press enter to continue"
press enter to continue:
If I use this in a script, PowerShell will wait until I press Enter before continuing with the rest of the script. When I was writing batch files, I used Pause quite a bit, and it's what I use to get the same result in PowerShell.
By default the Read-Host cmdlet uses simple strings. But you can also use the -asSecureString parameter, which instructs the cmdlet to convert the entered string as a secure string:
PS C:\> $pwd=read-host "Enter a password
for the new user" -asSecureString
Enter a password for the new user: ***********
PS C:\> $pwd
That parameter also instructs the cmdlet to mask the entered string. I can now use $pwd in any cmdlet or PowerShell expression that requires a secure string.
Jeffery Hicks is a Microsoft MVP in Windows PowerShell, Microsoft Certified Trainer and an IT veteran with over 20 years of experience, much of it spent as an IT consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He works today as an independent author, trainer and consultant. Jeff writes the popular Prof. PowerShell column for MPCMag.com and is a regular contributor to the Petri IT Knowledgebase and 4SysOps. If he isn't writing, then he's most likely recording training videos for companies like TrainSignal or hanging out in the forums at PowerShell.org. Jeff's latest books are Learn PowerShell 3 in a Month of Lunches, Learn PowerShell Toolmaking in a Month of Lunches and PowerShell in Depth: An Administrators Guide.
You can keep up with Jeff at his blog http://jdhitsolutions.com/blog, on Twitter at twitter.com/jeffhicks and on Google Plus (http:/gplus.to/JeffHicks)