Chapter 12. User Interaction
12.0. Introduction
While most scripts are designed to run automatically, you will frequently find it useful to have your scripts interact with the user.
Tip
The best way to get input from your user is through the arguments and parameters to your script or function. This lets your users to 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.
12.1. Read a Line of User Input
Problem
You want to use input from the user in your script.
Solution
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 C:\MyDirectory
Discussion
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 culturally aware scripts, see Recipe 12.6 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access