How to get Caps Lock status on remote computer using powershell

微笑、不失礼 提交于 2021-02-05 10:43:07

问题


I have tried the following command but I only get a value of False:

Invoke-Command -ComputerName Server01  -ScriptBlock {[console]::CapsLock} 

When I run [console]::CapsLock locally the command works.


回答1:


Using[Console]::CapsLock

The [Console]::CapsLock property can be read to get whether CapsLock is On or Off ($true or $false):

[Console]::CapsLock

You can also check the state of NumLock with [Console]::NumberLock as well.

Using MS Word

Seems that the remote session doesn't reflect whether CapsLock is on or off based on whether the physical keyboard has it on or off.

I was able to find another method but don't have a way to test it myself, and it requires Microsoft Word to be installed:

$word = New-Object -ComObject "Word.Application"

# Check CapsLock
$word.CapsLock

# Check NumLock
$word.NumLock

Using the System.Windows.Forms Namespace

A third method that might work for your needs would be to use the System.Windows.Forms namespace to read the caps lock setting.

# Make System.Windows.Forms available in Powershell
Add-Type -AssemblyName System.Windows.Forms

# Check CapsLock
[System.Windows.Forms.Control]::IsKeyLocked( 'CapsLock' )

# Check NumLock
[System.Windows.Forms.Control]::IsKeyLocked( 'NumLock' )

Using the Win32 API

You can also check the state using the Win32 API:

# Compile some quick C# so we can `P/Invoke` to the native library
$signature = @"
[DllImport("USER32.dll")]                            
public static extern short GetKeyState(int nVirtKey);
"@
$Kernel32 = Add-Type -MemberDefinition $signature -Name Kernel32 -Namespace Win32 -Passthru

# Check CapsLock
[bool]( $Kernel32::GetKeyState(0x14) )

# Check NumLock
[bool]( $Kernel32::GetKeyState(0x90) )

0x14 is the key id for CapsLock and 0x90 is the key id for NumLock. See this page for more information on making use of this API from .NET, and this page for the documentation of GetKeyState itself.

Doing it remotely

I could not find any reliable methods of doing this remotely, which makes sense, as CapsLock is a per session setting - not a system wide one. Even assuming there is a way to get the CapsLock status for a given active session, you could have several user sessions on one remote system at once, and it becomes difficult to know which session to look at for its CapsLock status.



来源:https://stackoverflow.com/questions/58822434/how-to-get-caps-lock-status-on-remote-computer-using-powershell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!