function Read-Character() {
if ($host.ui.RawUI.KeyAvailable) {
return $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown").Character
}
return $null
}
while($true){
$char = Read-Character
if ($char -ne $null){
write-host "You pressed $char"
}
}
When I run this code without the while loop, user input cannot be captured, but with the while loop a user input can be capture. Kindly help me understand this
When you post code, sample data, console output or error messages please format it as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.
function Read-Character() {
if ($host.ui.RawUI.KeyAvailable) {
return $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown").Character
}
return $null
}
$char = Read-Character
write-host "You pressed $char"
When I say user input cannot be captured outside the loop, the script return $null immediately after running the script without giving opportunity for me to press any key. Try running the script above
Because you’re not fast enough. … the code does not wait for a key press. It just checks if there is one. And if there is none the moment it runs it returns $null
Sure I might not be fast enough but why is it that when I’m inside a loop I have almost all the time to input a character. That is why I need the explanation
BTW: I actually did not test your script without the loop before. I did it now and it works just as expected. It waits for a key stroke and outputs it.