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.

One thought on “Restrict user input to yes or no in PowerShell while using Read-Host

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s