I have the following code in which the user has to enter either Y or N. If it's ENTER or anything else it requests again. The request is made every time on the same line.
My problem is that after I enter a wrong answer, when I'm prompted again I have to write over my previous answer. I've tried clearing the keyboard buffer before Read-Host with no luck. I don't want to use Clear-Host or a new line, it has to be on the same line. My question is, can I have a clean line after a wrong answer?
function clrkb
{
while($Host.UI.RawUI.KeyAvailable)
{
$Host.UI.RawUI.ReadKey() | Out-Null
}
}
$y_temp +=1;
do
{
clrkb
[Console]::SetCursorPosition(2,$y_temp);write-host Is this a service job? Y/N -f Magenta;[Console]::SetCursorPosition(29,$y_temp);$sj = read-host
}until($sj -eq "Y" -or $sj -eq "N")
function clrkb{
while(
$Host.UI.RawUI.KeyAvailable){$Host.UI.RawUI.ReadKey() | Out-Null
}
}
$y_temp +=1;
do{
clrkb
[Console]::SetCursorPosition(2,$y_temp);write-host Is this a service job? Y/N -f Magenta;[Console]::SetCursorPosition(29,$y_temp);[Console]::Write(' ' * [Console]::WindowWidth);[Console]::SetCursorPosition(29,$y_temp);$sj = read-host
}until($sj -eq "Y" -or $sj -eq "N")
Use spaces to overwrite wrong answer.
Maybe [Console]::WindowWidth
is not always big enough, so $sj.length
can be used instead.
function clrkb{
while(
$Host.UI.RawUI.KeyAvailable){$Host.UI.RawUI.ReadKey() | Out-Null
}
}
$y_temp +=1;
$sj='';
do{
clrkb
[Console]::SetCursorPosition(2,$y_temp);write-host Is this a service job? Y/N -f Magenta;[Console]::SetCursorPosition(29,$y_temp);[Console]::Write(' ' * $sj.length);[Console]::SetCursorPosition(29,$y_temp);$sj = read-host
}until($sj -eq "Y" -or $sj -eq "N")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.