I have a simeple loop to read for text and also detect the escape ESC [0x1b = chr(27)]
key, to quit.
The Expected Behaviour
<Enter loop>
<Enter any string, such as "AT" and hit Return>
# Some Output
<Repeat above OR>,
...
<Hit the ESC (Escape) key to exit loop>
<Exit Loop>
Actual Behaviour
I have to:
- Hit [Enter] button 2 times, after entering a string and before getting any output.
- ESC key to exit loop does not seem to work.
The Code:
do {
$key = if ($host.UI.RawUI.KeyAvailable) { $host.UI.RawUI.ReadKey('NoEcho, IncludeKeyDown') }
if ($port.IsOpen) {
$at = Read-Host
$port.Write("${at}`r")
} else {
Write-Host -Fo Yellow "[INFO] Port was Closed!"
break
}
} until ($key.VirtualKeyCode -eq 27) # Repeat until a 'ESC'
}
Q: How Can I fix the above to get the intended functionality?
(Why do I need to hit enter 2 times before the input string is processed?)
Experimenting, this one-liner is behaving very weird...
while (1) { if($host.UI.RawUI.ReadKey('IncludeKeyDown').VirtualKeyCode -eq 81) { break };$s=''; $s=Read-Host; if ($s -ne "w") { Write-Host ": $s" -Non | Out-Host } else { "Hit W!"} }
If you want to list the names and codes of all available keys, you can use:
1..255| ForEach-Object { '{0} = {1}' -f $_, [System.Windows.Forms.Keys]$_ }
# <output>
...
16 = ShiftKey
17 = ControlKey
18 = Menu
19 = Pause
...