Chapter 13. User Interaction


Although most scripts are designed to run automatically, you will frequently find it useful to have your scripts interact with the user.


The best way to get input from your user is through the arguments and parameters to your script or function. This lets your users run your script without having to be there as it runs!

If your script greatly benefits from (or requires) an interactive experience, PowerShell offers a range of possibilities. This might be simply waiting for a keypress, prompting for input, or displaying a richer choice-based prompt.

User input isn’t the only aspect of interaction, though. In addition to its input facilities, PowerShell supports output as well—from displaying simple text strings to much more detailed progress reporting and interaction with UI frameworks.

Read a Line of User Input


You want to use input from the user in your script.


To obtain user input, use the Read-Host cmdlet:

PS > $directory = Read-Host "Enter a directory name"
Enter a directory name: C:\MyDirectory
PS > $directory


The Read-Host cmdlet reads a single line of input from the user. If the input contains sensitive data, the cmdlet supports an -AsSecureString parameter to read this input as a SecureString.

If the user input represents a date, time, or number, be aware that most cultures represent these data types differently. For more information about writing culture-aware scripts, see Write Culture-Aware Scripts ...

Get Windows PowerShell Cookbook, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.