Powershell GetKeystate with outfile
Some thougts:


above all, using a user-level code pulling keyboard state periodically is much less reliable then kernel-level driver which OS pushes key events to
40 milliseconds sleep is much too high
if you could open the file handle once instead of each time a key is pressed, you'd get a significant performance boost, at the cost of taking care to close file after the script stops
if you could do file writing asynchronously (e.g. in a dedicated thread or leveraging an async API), this would reduce the risk of missing a key press because of I/O blocking
using a sound timer API allows resolution much better than what is achievable with thread sleeps
maybe it's worth increasing priority of the keylogger process, to reduce the risk of missing key due to thread context switch


(thanks Sam for your corrections)