How to get Caps Lock status on remote computer using powershell

前端 未结 1 514
不知归路
不知归路 2021-01-28 12:40

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

Invoke-Command -ComputerName Server01  -         


        
相关标签:
1条回答
  • 2021-01-28 12:56

    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.

    0 讨论(0)
提交回复
热议问题