2

I have a function which inserts a Y or N menu when called within my Powershell scripts. It uses a while loop to validate that either a Y or N value is entered. Everything works fine, however a new line is created each time an error is made. I could use cls and redisplay everything, but this is not the most ideal solution. Instead, I would like to find a way to redisplay the read-host prompt on the same line while clearing any previously entered answer. Here is my existing code:

# Begin function to display yes or no menu
function ynmenu {
    $global:ans = $null
    Write-Host -ForegroundColor Cyan "`n Y. [Yes]"
    Write-Host -ForegroundColor Cyan "N. [No]`n"
    While ($ans -ne "y" -and $ans -ne "n"){
        $global:ans = Read-Host "Please select Y or N"
    }
}
# End function ynmenu

I have a few other dynamically populated menus which leverage this methodology. Finding a solution to this would resolve the issue with those as well.

4
  • To be clear, when the user provides input (a carriage return, or enter), if not "Y" or "N," you want to remain on the line above, instead. Having no visible entry prior? Commented Nov 17, 2016 at 19:53
  • If anything is entered other than a "y" or an "n" including enter or no entry, I would like the prompt to redisplay on the same line. It would also need to clear the previous entry. For example, if someone typed yes or no or anything else it would not be valid. So that text would need to be cleared as well. Commented Nov 17, 2016 at 19:59
  • You aren't going to be able to "move" the cursor, or clear an individual line like that (not easily, at least - it's possible, but rather involved). The most practical method of achieving, purely visually, what you're asking for is to clear-screen, and rewrite the prompts and read-host. See this question for a similar request. Otherwise, you're overcomplicating what sounds like a series of similar implementations for prompt-only requests. Commented Nov 17, 2016 at 20:00
  • 1
    Ok thanks. I know I can do it via clearing the screen, but I was trying to avoid that. Doing so is not the end of the world though. Commented Nov 17, 2016 at 20:05

1 Answer 1

1

I don't think there's any simple way to do that.

But for a yes/no response, you can use $PSCmdlet.ShouldContinue($Query, $Caption) instead, as long as the scope you're in (function, script, etc.) defined the attribute [CmdletBinding(SupportsShouldProcess=$true)]. This shows an appropriate yes/no prompt in ISE and in the console host and avoids manual processing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.