PowerShell: Toggle "Num Lock" on and off.
Solution 1
I experienced the same on/off flicker you did.
This works fine for me though, give it a try:
$wsh = New-Object -ComObject WScript.Shell
$wsh.SendKeys('{NUMLOCK}')
Solution 2
For what it is worth, from the perspective of the keyboard, the OS sends a set and then a reset of the toggle key (caps, scroll lock, numlock) when using [System.Windows.Forms.SendKeys]::SendWait("{CAPSLOCK}")
, but only sends a single event using WScript.Shell
.
Solution 3
Stumbled here looking for a way to keep Num Lock
ON eternally (apparently the word "lock" doesn't mean much 🤷♂️). This script checks Num Lock
status every 2 seconds, and switches it back on if it's been turned off:
$wsh = New-Object -ComObject WScript.Shell
while($true){
if ([console]::NumberLock -eq $false) {
$wsh.SendKeys('{NUMLOCK}')
}
Start-Sleep 2
}
I think it would be a good candidate for converting into a standalone tiny .exe using PS2EXE.
Vippy
Updated on November 30, 2021Comments
-
Vippy over 2 years
I would like to be able toggle on and off the "Num Lock" key on the keyboard. I have tried multiple examples around the web and here, with no success. This is the closest thing I've got to a solution:
[void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms") [System.Windows.Forms.SendKeys]::SendWait("{NUMLOCK}")
The above code looks like it might work and I see the "Num Lock" indicator on my keyboard flash for a second but it doesn't "stick".