HomeBlogMagic

Keypress Skript für Powershell

Für Langzeittests auf einem PC ist es manchmal sinnvoll einen Bildschirm oder ähnliches offen zu halten um den Verlauf zu sehen, oder auch um Login Events zu vermeiden.

Einige Windows Systeme sind so eingerichtet dass Sie ausschalten, ausloggen, oder in den Lockscreen bzw. Sleep übergehen wenn keine Userinteraktion erfolgt.

Dafür kann dieses Powershell-Skript abhilfe schaffen, das alle 60 Sekunden ESC drückt.
Es ist aber nur für einfache Systeme gedacht und ist nicht überall anwendbar.

Add-Type @'
using System;
using System.Runtime.InteropServices;

public static class NativeInput3
{
    [StructLayout(LayoutKind.Sequential)]
    public struct INPUT
    {
        public uint type;
        public INPUTUNION U;
    }

    [StructLayout(LayoutKind.Explicit, Size = 32)]
    public struct INPUTUNION
    {
        [FieldOffset(0)]
        public KEYBDINPUT ki;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct KEYBDINPUT
    {
        public ushort wVk;
        public ushort wScan;
        public uint dwFlags;
        public uint time;
        public UIntPtr dwExtraInfo;
    }

    [DllImport("user32.dll", SetLastError = true)]
    public static extern uint SendInput(
        uint nInputs,
        INPUT[] pInputs,
        int cbSize
    );

    public const uint INPUT_KEYBOARD = 1;
    public const uint KEYEVENTF_KEYUP = 0x0002;

    public static uint PressA()
    {
        INPUT[] inputs = new INPUT[2];

        inputs[0].type = INPUT_KEYBOARD;
        inputs[0].U.ki.wVk = 0x1b;

        inputs[1].type = INPUT_KEYBOARD;
        inputs[1].U.ki.wVk = 0x1b;
        inputs[1].U.ki.dwFlags = KEYEVENTF_KEYUP;

        int size = Marshal.SizeOf(typeof(INPUT));

        return SendInput(2, inputs, size);
    }
}
'@

Start-Sleep 5

while(1)
{
    $result = [NativeInput3]::PressA()
    $errorCode = [Runtime.InteropServices.Marshal]::GetLastWin32Error()

    Write-Host "SendInput Ergebnis: $result"
    Write-Host "Fehlercode: $errorCode"
    Start-Sleep 60
}