Powershell console readkey

Powershell Console ReadKey

Powershell provides the ReadKey function to read a single key from the console input. This function is commonly used to pause the script execution and wait for user input. Here is an example:

    
      $keyInfo = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
      $key = $keyInfo.Character
      
      if ($key -eq "Y" -or $key -eq "y") {
          Write-Host "User pressed Yes"
      }
      elseif ($key -eq "N" -or $key -eq "n") {
          Write-Host "User pressed No"
      }
      else {
          Write-Host "Invalid input"
      }
    
  

In the above example, the ReadKey function reads a single key from the console and stores it in the $keyInfo variable. The “NoEcho,IncludeKeyDown” parameter ensures that the entered key is not displayed on the console. The actual key value is extracted from the $keyInfo.Character property.

The code then checks the value of the $key variable to perform different actions based on user input. If the user presses “Y” or “y”, it displays “User pressed Yes”. If the user presses “N” or “n”, it displays “User pressed No”. Otherwise, it displays “Invalid input”.

You can customize the logic based on your requirements. The ReadKey function allows you to capture any keypress, including function keys and special keys.

Leave a comment