Avoid Read-Host

by Sep 18, 2017

Do you use Read-Host to receive user input? If you do, rethink. Read-Host always prompts a user, and there is no way to automate scripts that use Read-Host:

$City = Read-Host -Prompt 'Enter City'

A much better easy way would look like this:

param
(
    [Parameter(Mandatory)]$City
)

This creates a mandatory parameter. If the user does not supply it, a prompt is created, very similar to Read-Host. Yet, the user can always submit the parameter to his script and automate it. Just make sure there is only one param() statement, and that it is at the beginning of your script. Use commas to separate multiple parameters.

And if you don’t like the standard prompt produced by param(), check out this:

param
(
    $City = (Read-Host -Prompt 'Enter City')
)

Here, you have full control over the prompting, yet the user can again submit the argument via parameter, and run the script unattended.

Twitter This Tip! ReTweet this Tip!