Is there a way to programmatically add a logon or logoff script in Windows? I don't want to use any graphical programs, everything's supposed to happen without the user noticing anything.
Also, I want to run the scripts only when a certain user logs in/out. It shouldn't trigger for every user on the system.
Attempted solutions:
Adding the command to the registry, as per this answer. It seems that adding the command to
HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\System\Scripts\Logoff\0\0
isn't enough. I found I also need to add the same command atHKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\S-1-5-21-57470242-2825662697-3518406308-1003\Scripts\Logoff\0\0
, and possibly also modify%WINDIR%\System32\GroupPolicy\User\Scripts\scripts.ini
, otherwise the command simply isn't executed.I've stopped pursuing this solution because I don't know what the registry key
S-1-5-21-57470242-2825662697-3518406308-1003
is. Is this a random sequence of digits? Is it always the same text? Will it work if I use this on a different PC?Modifying
%WINDIR%\System32\GroupPolicy\User\Scripts\scripts.ini
as per this answer. Something very odd is happening here. I can see this file in explorer. It exists. I can open it, and, with admin privileges, can use notepad to modify it. But when I try to access it from within a python script, I get a FileNotFoundError, even if given admin privileges. (Traceback:FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Windows\\System32\\GroupPolicy\\User\\Scripts\\scripts.ini'
P.S.: I'm not using double backslashes, python just displays them like that)Creating a startup task using
SCHTASKS
. I gave up on this because it looks like SCHTASKS only supports logon tasks, but not logoff tasks.
schtasks
will handle logoff. Link the task to event id 4647 - User initiated logoff or 4634 - An account was logged off – DavidPostill♦ Aug 30 '16 at 22:04SCHTASKS /create /tn test /tr "C:\Python34\python.exe 'D:\test.py'" /ec SYSTEM /sc ONEVENT /mo "*[System/EventID=4634]"
, but for some reason it's not being executed when I log out. It runs successfully if I doSCHTASKS /run /tn test
though. What am I doing wrong? – Aran-Fey Aug 30 '16 at 22:36schtasks /query /v /tn test /fo list
and everything looks ok, but I noticed that thelast run time
doesn't change when I log out. I guess there must be something wrong with the xpath*[System/EventID=4634]
. – Aran-Fey Aug 31 '16 at 7:33