A Tip for Writing Better Scripts with PowerShell's Read-Host cmdlet

In a previous article I guided you through some variations on using Read-Host to prompt for user input. It’s not too surprising that I couldn’t leave the topic alone. I just had to keep working with it, and I came up with something else that I hope you’ll fine equally helpful. I wanted to take Read-Host to the next level and create a tool that will let you write better scripts.

Let’s say you are using Read-Host in a script or function to prompt for additional information. You might start with something like this:

PowerShell

1

$name=Read-Host"Enter a user name"

You most likely need to validate it, perhaps to make sure something was entered.

PowerShell

1

2

3

4

5

6

7

if($name){

#code to continue

#...

}

else{

Write-Warning"You didn't enter a user name"

}

Another option is to use one of the parameter validation checks. They are really variable validation tests, and you can use them anywhere.

PowerShell

1

[ValidatePattern("\w+")]$name=Read-Host"Enter a user name"

Using a validation test (Image Credit: Jeff Hicks)

I didn’t use ValidateNotNullorEmpty because even if you press Enter, Read-Host writes a 0 length string to the pipeline, which technically passes the NotNullorEmpty test. So I wanted a Read-Host prompt that offered built-in validation. I also wanted to take some of the features of the $host.ui.Prompt() method like a title. And finally, I liked the idea of adding color to the prompt to make it stand out. Here’s my function, where I call Read-HostSpecial, as well as an alias.

The function uses several parameter sets for the different validation tasks you might want. At a minimum, all you need to enter is a message prompt. Instead of using Read-Host, I use the Readline() method to get the input.

PowerShell

1

$r=$host.ui.ReadLine()

I do this because I’m using Write-Host to display the prompt text as well as an optional title.

PowerShell

1

2

3

4

5

6

$Text=@"

$(if ($Title) {

"$Title`n$("-" * $Title.Length)"

})

$Prompt :

"@

In the here string I have inserted some logic in the form of an If statement. If there is a title, then it is inserted along with a string of —- that match the length. By using Write-Host, I can take advantage of its ForegroundColor parameter.

PowerShell

1

2

3

4

5

6

7

8

9

$paramHash=@{

NoNewLine=$True

Object=$Text

}

if($PromptColor){

$paramHash.Add("Foregroundcolor",$PromptColor)

}

#display the prompt

Write-Host@paramhash

Using Read-HostSpecial (Image Credit: Jeff Hicks)

You can also enter text as a secure string.

Entering a secure string (Image Credit: Jeff Hicks)

But the real part of the function are the validation tests. You can test for null or empty values, and I count a 0 length string as empty as well as anything that is only whitespace.

Validating not null or empty (Image Credit: Jeff Hicks)

You can validate on a regular expression pattern:

Validating on a pattern (Image Credit: Jeff Hicks)

You can validate on a set:

Validating on a set (Image Credit: Jeff Hicks)

And you can validate on a range. Enter a comma separated list of the low and high values.

Validating a range (Image Credit: Jeff Hicks)

In the function I wrote my own validation tests primarily so that I could write my own error messages should they fail. I suppose you might want to run multiple validation tests on the input, but this version won’t do that. But you are more than welcome to take the code and run with it. In fact, even if you don’t really have a need for the function, I’m hoping you picked up a PowerShell scripting trick or two.

If you find a use for this function, I hope you’ll share your experience in the comments. Enjoy!

MEMBER LOGIN:

BECOME A PETRI MEMBER:

About the Contributor

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, teacher and consultant. Jeff has written for numerous online sites and print publications and is a frequent speaker at technology conferences and user groups. His latest book is PowerShell Scripting and Toolmaking.