I was reading the Stack Overflow (PowerShell) forum when I happened on a question that I decided I would take on. It reminded me of an old post I had written. In that post, Countdown Options, I wrote a countdown that overwrote itself as it counted down. Here’s s GIF from that post.
In the question on Stack Overflow, someone wanted to get away from the way Do-Until works. Here’s their, modified-by-me question:
I have this simple bit of code in a PS script where I want to get a simple yes or no answer…The problem is that when user inputs something other than y or n it reprompts on new line…How can I avoid the new line and make the code as simple and easy to understand as possible?
I didn’t bother taking my time to explain that this is how it works and that they should expect more from their users. Instead, I set out to use what I learned from my countdown article. Before we get to that solution, let’s look at how this works before the changes I implemented.
Do { $Answer = Read-Host -Prompt 'Found missing roles. Install them now? (y/n)' } Until ($Answer -eq 'y' -or $Answer -eq 'n')
According to the OP, the problem with the above option and below results is that it’s re-prompting on the next line if the answer doesn’t match “y” or “n.” That needed to be avoided, if possible.
Found missing roles. Install them now? (y/n): 1 Found missing roles. Install them now? (y/n): 2 Found missing roles. Install them now? (y/n): 3 Found missing roles. Install them now? (y/n): 4 Found missing roles. Install them now? (y/n): Found missing roles. Install them now? (y/n): Found missing roles. Install them now? (y/n): a Found missing roles. Install them now? (y/n): b Found missing roles. Install them now? (y/n): c Found missing roles. Install them now? (y/n): n
In my example, we overwrite the previously entered value. Take a look at the slight modifications I’ve made to the code. Then, take a look at the GIF made for this article.
$Cursor = [System.Console]::CursorTop Do { [System.Console]::CursorTop = $Cursor Clear-Host $Answer = Read-Host -Prompt 'Found missing roles. Install them now? (y/n)' } Until ($Answer -eq 'y' -or $Answer -eq 'n')
And with that, my work is done here, and over there on Stack Overflow. Well, until the next question, where I can hopefully make a positive impact.