PowerShell – ReadHost Continue on ‘y’

Occasionally, we are required to gather data from the most unreliable element of the computing milieu: the user.  The goal is to acquire to appropriate response, while discarding junk reponses, and preventing the user from blowing up the entire automation process.  The while loop below does just that, while maintaining its girlish figure.

$query = $null
while (!($query -ieq "y" -or $query -ieq "n"))
{
    $query = Read-Host "Do the thing? [y/n]"
}
if ($query -ieq "y")
{
    #Do the thing
}
else
{
    #Don't do the thing
}

Leave a Reply