How to test for yes/no

I want to read-host “Yes/no” and only accept those values, or Y/N and then test the condition to make powershell do one action if the input is Yes and another if the input is No.

do { $myInput = (Read-Host 'Bla bla? (Y/N)').ToLower() } while ($myInput -notin @('y','n'))
if ($myInput -eq 'y') {
'branch for yes'
} else {
'branch for no'
}

[pre]

$Title = “Welcome”
$Info = “Enter your choice”
$options = [System.Management.Automation.Host.ChoiceDescription[]] @("&Yes", “&No”)
[int]$defaultchoice = 1

$option = $host.UI.PromptForChoice($Title, $Info, $Options, $defaultchoice)

switch($option)
{
0 { Write-Host “Yes - Write your code”}
1 { Write-Host “No - Write your code”}
}

[/pre]

Another approach could be this …

$title = ‘You Decide’
$message = ‘Yes or no … you decide’
$yes = New-Object System.Management.Automation.Host.ChoiceDescription “&yes”, ‘yes?’
$no = New-Object System.Management.Automation.Host.ChoiceDescription “&no”, ‘no?’
$cancel = New-Object System.Management.Automation.Host.ChoiceDescription “&cancel”, ‘no decision at all?’
$options = [System.Management.Automation.Host.ChoiceDescription]($yes, $no, $cancel)
$result = $host.ui.PromptForChoice($title, $message, $options, 0)

I like it because it looks like the standard Powershell choices … and you even can define a default choice. :wink:

Ideally, this is a good approach in terms of best practices.

There must be an easier way? Like… I altso want the script to run over and over if the user does not apply either yes or no.

Did you at least try the code? With my code suggestion you cannot enter something else. It has to be one of the predefined choices.

As for…

I altso want the script to run over and over if the user does not apply either yes or no.

… You define those as the only options.

Olaf’s code does exactly that, or just use a simple Do/While, or Do/Until loop

Clear-Host
do{ $YesNoResponse = Read-Host "Do you want to check limits for another user? (Y/N)" }
until($YesNoResponse -eq "n")

# Results

Do you want to check limits for another user? (Y/N): q
Do you want to check limits for another user? (Y/N): q
Do you want to check limits for another user? (Y/N): q
Do you want to check limits for another user? (Y/N): q
Do you want to check limits for another user? (Y/N): sdf
Do you want to check limits for another user? (Y/N): dfs
Do you want to check limits for another user? (Y/N): y
Do you want to check limits for another user? (Y/N): n