Read-Host Blocks Automation

Using Read-Host to ask for user information can be problematic because it prevents scripts from running unattended. A better way could be to wrap Read-Host in the param() block. This way, the information can be submitted via arguments for unattended operation, and prompted for interactive usage:

    $Name = $(Read-Host -Prompt 'Enter your name'),
    $Id = $(Read-Host -Prompt 'Enter your ID')

"You are $Name and your ID is $Id"

When you run above script, it prompts you with all the freedom Read-Host provides to design a prompt text. You can however also run the script with parameters:

PS> C:\myscript.ps1 –Name test –Id 12 

If you do not need custom prompting, you can go even simpler, and declare parameters as mandatory by adding [Parameter(Mandatory)] above each parameter variable.

Twitter This Tip! ReTweet this Tip!