I am trying to clean up some code that I’ve written. I’ve been asked if I could further foolproof the logic of a switch that I have within it, which forces the user to enter a number that corresponds with an action. The problem seems to actually lie in the setup for the switch, a while loop. Here is an example of what I’m having trouble with:
[int]$choice = 0 while ($choice -lt 1 -or $choice -gt 2) { Write-Host "Enter the option you wish to select" Write-Host "1. Do A" Write-Host "2. Do B" [int]$choice = Read-Host "Enter number here" }
Then it goes into the actual switch itself which processes the input.
The problem I’m having is that while I’m trying to force an integer and use a while loop to ensure this works, if a “string” is entered, the while loop fails completely. You can enter any number from -500 to 1,000,000 and it will continue to loop until it receives a 1 or 2. But a string of any kind will break it.
I tried adding:
-or $choice -is [string]
But no luck there either.
How can I force this variable to be an integer? Or alternatively, is there a better way to force input and throw it into a switch? Obviously while keeping it foolproof.
submitted by /u/brian1183
[link] [comments]
The post Problem with while logic(forcing an integer) appeared first on How to Code .NET.