Read-Host


Is there a proper use case?



Posted by Tim Sullivan on 19 Apr 2017

The Challenge

Many times I will find read-hosts written in old scripts of mine or scripts of my colleagues, and often times, it will cause me to shudder. It’s not that read-host is inherently bad, there are many different situations for using it. For instance, if your script is always meant to be interacted with from the console and you want to gather data after the initial invocation, read-host might be your cmdlet. However, most of the time, I find that read-host was used as a crutch to gather input that could have been gathered in a different, better way.

The Solution

I have found that created a parameter block is almost always superior (at least for data that will be known to the user at the start of the script). With a parameter block, we can make a parameter mandatory (meaning that if it isn’t entered, we will prompt just like read-host). We can modify the prompt with HelpMessage, just like with the -Prompt parameter of the read-host cmdlet. We can validate the info, just like we can after we use read-host.

In addition to all of that, with a parameter block, we can pass values from the pipeline, we can run multiple sets against one cmdlet, and we allow for more flexibility. Without a parameter block, we are forced to interact with the script, but with a parameter block, we can automate tasks, we can query other scripts for info, etc.

In the future, I will expand with some more info about parameters.