Typically, key press detection is supported only in true console windows, so this approach won’t work for the PowerShell ISE and other PowerShell hosts.

However, PowerShell can borrow a type from the Windows Presentation Foundation that can check the state of any key. This way, it becomes trivial to implement an “abort” key that works in any PowerShell script, whether it runs in the console, Visual Studio Code, or PowerShell ISE:

Add-Type -AssemblyName WindowsBase
Add-Type -AssemblyName PresentationCore

# choose the abort key
$key = [System.Windows.Input.Key]::LeftCtrl
  
Write-Warning "PRESS $key TO ABORT!"
  
do
{
  $isCtrl = [System.Windows.Input.Keyboard]::IsKeyDown($key)
  if ($isCtrl)
  {
    Write-Host
    Write-Host "You pressed $key, so I am exiting!" -ForegroundColor Green
    break
  }
  Write-Host "." -NoNewline
  Start-Sleep -Milliseconds 100
} while ($true)

Simply pick your “abort” key in the variable $key. The example uses the left CTRL key.


Twitter This Tip! ReTweet this Tip!

Anonymous