Is there a way to shorten this?

The goal is to toggle an LED on the keyboard, I currently have this:

(New-Object -c WScript.Shell).SendKeys('{NUMLOCK}')

For japanese keyboard NUMLOCK could be replaced by KANA, but other than that, can this command be shortened?

Posted Mar 5, 2018, 6:12 PM UTC

518
spyingwind•

With out resorting to WScript:

$Code = @"
private const byte VK_NUMLOCK = 0x90;
private const uint KEYEVENTF_KEYUP = 0x2;

[DllImport("user32.dll", EntryPoint="keybd_event", SetLastError=true)]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);

[DllImport("user32.dll", EntryPoint = "GetKeyState", SetLastError = true)]
static extern short GetKeyState(uint nVirtKey);

public static void SetNumLockKey(bool newState)
{
    bool scrollLockSet = GetKeyState(VK_NUMLOCK) != 0;
    if (scrollLockSet != newState)
    {
        keybd_event(VK_NUMLOCK, 0, 0, 0);
        keybd_event(VK_NUMLOCK, 0, KEYEVENTF_KEYUP, 0);
    }
}

public static bool GetNumLockState() // true = set, false = not set
{
    return GetKeyState(VK_NUMLOCK) != 0;
}
"@

$app = Add-Type -MemberDefinition $code -Name LockKeys -Namespace Win.API -ReferencedAssemblies System.Windows.Forms -PassThru
[Win.API.LockKeys]::SetNumLockKey($false)
[Win.API.LockKeys]::SetNumLockKey($true)
4
MinecraftChrizzOP•

Are there any major disadvantages to resorting to WScript? It's a lot shorter with WScript.

2
Ta11ow•

You'll generally get more flexibility if you avoid WScript. Wscript was designed mainly with VBScript and batch files in mind, to my knowledge.

Powershell's solutions, while more verbose, tend to be more flexible, stable, and easier to work with.

3
MinecraftChrizzOP•

For my use case I really need something short.

I'm trying to make a USB HID that when plugged in runs a script based on the operating system. However, there is no way for the HID device to directly find out the operating system of the host, in fact, the only controllable communication from the host to the HID is through the 'lock' buttons, so I thought of the following work around:

The USB presses win+r and types a short command to toggle one of the 'lock' buttons. If the HID detects that a 'lock' key has been sent by the host, it knows that the host runs windows, so it runs the windows script.

Since HIDs have to type letter by letter, I want the commands to be short, such that the whole process is quicker, so for example: powershell New-Object -c WScript.Shell|% s* '{NUMLOCK}'

3
spyingwind•

Another way entirely is to do this much more easily:

iwr -Uri "http://localhost/somescript.ps1" -OutFile .\somescript.ps1
icm .\somescript.ps1

Expanded out:

Invoke-WebRequest -Uri "https://localhost/somescript.ps1" -OutFile .\somescript.ps1
Invoke-Command .\somescript.ps1
3
Ta11ow•

I mean, fair enough... but there has got to be a quicker way to accomplish this.

But that, I think, lies a bit beyond the general purview of PowerShell. :)

2
spyingwind•

Something shorter?

$C=@"
private const byte NL = 0x90;private const uint KU = 0x2;
[DllImport("user32.dll", EntryPoint="keybd_event", SetLastError=true)]static extern void ke(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
[DllImport("user32.dll", EntryPoint="GetKeyState", SetLastError=true)]static extern short GKS(uint nVirtKey);
public static void SNL(bool nS){bool nLS = GKS(NL) != 0;if (nLS != nS){ke(NL, 0, 0, 0);ke(NL, 0, KU, 0);}}
"@
$a=Add-Type -MemberDefinition $C -Name LK -Namespace W.A -ReferencedAssemblies System.Windows.Forms -PassThru
[W.A.LK]::SNL($false)
2
TheIncorrigible1•

You can do without the initial variable declaration for the type definition and -PassThru is unnecessary entirely with the variable assignment.

2
ka-splam•

51 to 44:

New-Object -c WScript.Shell|% s* '{NUMLOCK}'

There's no default alias for new-object, you can't skip the verb because it's not 'get', it doesn't make a com object if you don't use -c, and removing the spaces or quotes makes it fall over.

Unless you want to use a third party tool I'd be surprised if it can be shortened.

3
Ta11ow•

Yeah, and although you can shorten it, I'd avoid doing so if it's something you have in a script somewhere. If you're doing it on the command line, I'd just define it in full and assign it to a custom function in your PowerShell profile script which has a short (three-characters or so) alias. Function could be defined like so:

function Send-NumLock {
    [CmdletBinding()]
    [Alias('snuml')]
    param()
    (New-Object -c WScript.Shell).SendKeys('{NUMLOCK}')
}
6
MinecraftChrizzOP•

Wow didn't expect a solution so quickly!

How does this part work? is s* an alias for SendKeys?

|% s*

2
ka-splam•

|% is | ForEach-Object and the usual use of it is with a scriptblock like |% -Process {..} to calculate for each pipeline object, but it also has a different parameter set where you can give it a property or method name, and it will expand the property or call the method for each object in the pipeline.

s* is a wildcard search, and if you look at the available proeperties and methods on that object:

PS C:\> New-Object -c WScript.Shell | Get-Member


   TypeName: System.__ComObject#{41904400-be18-11d3-a28b-00104bd35090}

Name                     MemberType            Definition
----                     ----------            ----------
AppActivate              Method                bool AppActivate (Variant, Variant)
CreateShortcut           Method                IDispatch CreateShortcut (string)
Exec                     Method                IWshExec Exec (string)
ExpandEnvironmentStrings Method                string ExpandEnvironmentStrings (string)
LogEvent                 Method                bool LogEvent (Variant, string, string)
Popup                    Method                int Popup (string, Variant, Variant, Variant
RegDelete                Method                void RegDelete (string)
RegRead                  Method                Variant RegRead (string)
RegWrite                 Method                void RegWrite (string, Variant, Variant)
Run                      Method                int Run (string, Variant, Variant)
SendKeys                 Method                void SendKeys (string, Variant)
Environment              ParameterizedProperty IWshEnvironment Environment (Variant) {get}
CurrentDirectory         Property              string CurrentDirectory () {get} {set}
SpecialFolders           Property              IWshCollection SpecialFolders () {get}

The wildcard s*only matches SpecialFolders and SendKeys, but we also give it a parameter of a string, we have to be looking for a method, so it only matches SendKeys.

And as long as the wildcard matches a single thing, % is happy, so no it's not an alias for SendKeys but effectively yes it works like that.

4
MinecraftChrizzOP•

Ah that's quite clever, thanks for the explanation!

2