Code explanation

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

B Affoe,
Welcome to the forum. :wave:t3:

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.

Thanks in advance

How to format code in PowerShell.org 1 <---- Click :point_up_2:t4: :wink:

( !! Sometimes the preformatted text button hides behind the settings gear symbol. :wink: )

What do you mean exactly by that? It works for me just as expected. If I run the code without the loop the code captures one key hit and outputs it. :man_shrugging:t3:

What would you expect? :thinking:

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. :wink: :stuck_out_tongue_winking_eye: … 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 :man_shrugging:t3:

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. :man_shrugging:t3:

Alright, thanks for the feedback

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.