For whatever reason the While loop works by itself, the Switch statement works by itself, when I combine them.. the While loop works ok, the Switch statement though.. not so much.
y or n are only values the While loop accepts, the problem is that when I give it y or n, none of the code gets executed, the script just finishes.
PowerShell version is 5.1.
While (($UserInput = Read-Host -Prompt "Are you sure? (y/n)") -notmatch '^n$|^y$') {
Switch ($UserInput) {
'y' {
Try {
Write-Output "Success."
}
Catch {
Write-Output "Error."
}
}
'n' {
Write-Output "Cancelled."
}
}
}
yor ann[3] if it fails the test [anything other than ayor an], it tests against a y or n !!!!! [grin] ///// you already made sure it would NOT have either of those in it ... so why do you expect either of the two switch values to trigger? you would need to include adefaultto handle non-matches. ///// also, thetry/catchdoes nothing there ... what are you trying to do with that?Write-Outputcmdlets.switchbecause thewhilesays "only run the loop code IF neither an "n" nor a "y" is entered.not -notmatch, as shown below by @Mudit Bahedia and made some changes, by adding return to each output, otherwise the loop would not end.