Prof. Powershell

Do You Read Me?

Even sans GUI, Powershell can be made to work interactively. The trick is the Read-Host cmdlet.

PowerShell 1.0 is intended to be used as a management console. As such, it does not have a graphical interface. There are no input or message boxes as you have in VBScript, although those items can be created through the use of WinForms or through third-party snapins. 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
SRV03
PS C:\>

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 will 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
SRV03
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 space bar 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:

PS C:\>

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 its' how I 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
System.Security.SecureString

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.

About the Author

Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular

SharePoint Watch

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.