title: Listen for a key press with Powershell, but don't wait for it
body: <p>I'm trying to write a script that toggles the caps lock key periodically, but I also want to be able to toggle the script because it causes some issues with other functionality (like alt tabbing, and rolling over windows in the task bar to see a preview)</p>
  
  <p>The script I have so far is</p>
  
  <pre><code>:outer while($true){
      do{ 
      echo "Toggle with F12";
      $x = [System.Console]::ReadKey() 
      }while( $x.Key -ne "F12" )
      while($true){
          $wsh = New-Object -ComObject WScript.Shell
          $wsh.SendKeys('{CAPSLOCK}')
          sleep 0.3
          [System.Runtime.Interopservices.Marshal]::ReleaseComObject($wsh)
          Remove-Variable wsh
          if ($Host.UI.RawUI.KeyAvailable) {
              $key = $Host.UI.RawUI.ReadKey()
              if($key.Key -ne "F12"){
                  break outer
              }
          }
      }
  }
  </code></pre>
  
  <p>The script waits for the user to press F12, and then once they press F12 I want it to start toggling the caps lock key ever 0.3 seconds until the user presses F12 again. Ideally, I want this to happen in the background, but I don't know if that's possible. I don't want the user to have to have the console window open to toggle the script.</p>
  
  <p>The way this runs now, after the user presses F12 the script will toggle capslock once and then exit. If I remove the conditional after Remove-Variable, the script will run as I want it to except the only way it can be stopped is if the console window is closed.</p>