I have created several menu scripts for executing several jobs. But they all have the same problem:
When you press a key, it's job is executed not once, but twice or even thrice
My code is as follows:
Function Write-Menu{
Write-Host ""
Write-Host -BackgroundColor Black -NoNewline "Enter"; Write-Host " Job description"
Write-Host ""
Write-Host ""
Write-Host -BackgroundColor Black -NoNewline " A "; Write-Host " Job 2 description"
Write-Host ""
Write-Host -BackgroundColor Black -NoNewline " B "; Write-Host " Job 3 description"
Write-Host ""
Write-Host -BackgroundColor Black -NoNewline " C "; Write-Host " etc.."
}
Write-Menu
Do {
$key = $null
$key = $Host.UI.RawUI.ReadKey()
Sleep -Milliseconds 250
If ($key.Character -eq 13) {
#Do Something..
}
If ($key.Character -eq etc) {
#etc..
}
Clear-Host
Write-Menu
} Until(!($CloseMenu = "false"))
I have tried everything to stop it but nothing fixed this issue. I don't see anyone else having this issue either..
It seems to save your pressed key code for 2 or 3 loops regardless of any delay / sleep time, the variable being cleared / reset and regardless of what code is within it. Even if I start a java process that closed 8 hours later is still does that. I have no idea why this is even happening.
Only closing the menu seems to work well ^^
I have thought of setting up the loop differently but I can't think of any setup. Can I have some assistance? Thanks
$Host.UI.RawUI.ReadKey()
reads key pressed, key released, a combination of the two, and can display them on the console, hence your "2-3 keys" read.
To control better how it behaves you can use the options parameter which is a bitmask of one or more of the following:
IncludeKeyDown
IncludeKeyUp
NoEcho
By passing "NoEcho, IncludeKeyDown" to ReadKey you basically are telling it to ignore key up events, and not echo anything.
More about it here : Source from MSDN
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.