Use this code to get Yes/No confirmation from the user.
Two flavors: Asking once or until valid option is typed.
# Snippet ::: Get User Confirmation -_- # PowerShellExamples.com # Get User Confirmation - asking once -_- Write-Host "Are you Sure You Want To Proceed?:" -ForegroundColor Yellow $confirmation = Read-Host "Y(es)/N(o):" switch -regex ($confirmation.ToLower()) { "^y(es)?$" { $proceed = $true } "^n(o)?$" { $proceed = $false } default { $proceed = $null } } # take action from response -_- if([string]::IsNullOrEmpty($proceed)){ Write-Host "Selected Option - $confirmation - is not valid" }else{ if($proceed){ Write-Host "Proceed." }else{ Write-Host "Cancel Operation" } }
# Snippet ::: Get User Confirmation -_- # PowerShellExamples.com # Get User Confirmation - Until valid option is selected -_- do { Write-Host "Are you Sure You Want To Proceed?:" -ForegroundColor Yellow $confirmation = Read-Host "Y(es)/N(o):" switch -regex ($confirmation.ToLower()) { "^y(es)?$" { $proceed = $true } "^n(o)?$" { $proceed = $false } default { write-host "Option not valid. Try again" -ForegroundColor red $proceed = $null } } } while ($proceed -eq $null) # take action from response -_- if([string]::IsNullOrEmpty($proceed)){ Write-Host "Selected Option - $confirmation - is not valid" }else{ if($proceed){ Write-Host "Proceed." }else{ Write-Host "Cancel Operation" } }
# Sample : Scripting ::: Force Variable Declaration -_- # PowerShellExamples.com # Get User Confirmation - asking once -_- # Get User info Write-Host "Are you Sure You Want To Proceed?:" -ForegroundColor Yellow $confirmation = Read-Host "Y(es)/N(o):" # Evaluate response switch -regex ($confirmation.ToLower()) { "^y(es)?$" { $proceed = $true } "^n(o)?$" { $proceed = $false } default { $proceed = $null } } # take action from response -_- if([string]::IsNullOrEmpty($proceed)){ Write-Host "Selected Option - $confirmation - is not valid" }else{ if($proceed){ Write-Host "Proceed." }else{ Write-Host "Cancel Operation" } }
PS C:\>
Are you Sure You Want To Proceed?:
Y(es)/N(o):: Yes
Proceed.