Martin's technology blog – PowerShell
Blog content
Active categories:
- Tip (2)
- GPS (1)
- OpenStreetMap (1)
- OATH (1)
- Windows (1)
By date:
(No recent posts)
Blog calendar
Mo | Tu | We | Th | Fr | Sa | Su |
---|---|---|---|---|---|---|
<< Feb | Apr >> | |||||
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
2011-06-29 | Querying key states in PowerShell
Did you ever wonder how to check key states in a PowerShell script? This can be handy in situations where you want your script to behave slightly differently when, for example, the Shift key is pressed.
The first instinct would be to use something like the Windows.Forms.Control.ModifierKeys method, which even works for .NET console applications. However, in PowerShell said method always returns None, so that won't work.
Here's a slightly uglier method that provides a workaround:
function Get-KeyState([uint16]$keyCode)
{
$signature = '[DllImport("user32.dll")]public static extern short GetKeyState(int nVirtKey);'
$type = Add-Type -MemberDefinition $signature -Name User32 -Namespace GetKeyState -PassThru
return [bool]($type::GetKeyState($keyCode) -band 0x80)
}
The function can be used as follows:
$VK_SHIFT = 0x10
Write-Host "Shift key pressed:" (Get-KeyState($VK_SHIFT))
For more information on how to query other keys you can consult the documentation on the GetKeyState() function and Virtual Key Codes.