Chapter 13. User Interaction

13.0 Introduction

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

Note

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.

13.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 culture-aware ...

Get PowerShell Cookbook, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.