Restrict user input to yes or no in PowerShell while using Read-Host

This is not much but useful tip. Sometimes, while trying to read input from the user, you would want the response in yes/no (or y/n for that matter). You would not want users trying to enter anything or pressing any key by mistake which is mistaken for either yes/no. For this, we can use below specified simple code:

$YesOrNo = Read-Host "Please enter your response (y/n)"
while("y","n" -notcontains $YesOrNo )
 $YesOrNo = Read-Host "Please enter your response (y/n)"

Above example can also be modified to get limited set of choices from users.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s