How do you schedule a task in Windows XP to run when you shut down windows. Such that I want to run a simple command line program I wrote in c# everytime I shut down windows. There doesn't seem to be an option in scheduled tasks to perform this task when my computer shuts down.
Execute gpedit.msc (local Policies)
Computer Configuration -> Windows settings -> Scripts -> Shutdown -> Properties -> Add
SYSTEM
most likely? I need to to execute under some special account, because required pieces of information to successfully exec the script are only available for that special account. –
Faulkner MaxGPOScriptWait
–
Cerellia In addition to Dan Williams' answer, if you want to add a Startup/Shutdown script, you need to be looking for Windows Settings under Computer Configuration. If you want to add a Logon/Logoff script, you need to be looking for Windows Settings under User Configuration.
So to reiterate what Dan said with this information included,
For Startup/Shutdown:
- Run gpedit.msc (Local Policies)
- Computer Configuration -> Windows Settings -> Scripts -> Startup or Shutdown -> Properties -> Add
For Logon/Logoff:
- Run gpedit.msc (Local Policies)
- User Configuration -> Windows Settings -> Scripts -> Logon or Logoff -> Properties -> Add
Source: http://technet.microsoft.com/en-us/library/cc739591(WS.10).aspx
For those who prefer using the Task Scheduler, it's possible to schedule a task to run after a restart / shutdown has been initiated by setting the task to run after event 1074 in the System log in the Event Viewer has been logged. However, it's only good for very short task, which will run as long as the system is restarting / shutting down, which is usually only a few seconds.
- From the Task Scheduler:
Begin the task: On an event
Log: System
Source: USER32
EventID: 1074 - From the command prompt:
schtasks /create /tn "taskname" /tr "task file" /sc onevent /ec system /mo *[system/eventid=1074]
Comment: the /ec option is available from Windows Vista and above. (thank you @t2d)
Please note that the task status can be:
The operation being requested was not performed because the user has not logged on to the network. The specified service does not exist. (0x800704DD)
However, it doesn't mean that it didn't run.
/ec system
does not exist, but it is called /ru system
. see support.microsoft.com/en-us/kb/814596#bookmark-4 –
Alissaalistair ... /mo *[system/eventid=1074]
, not .../mo *[system/evendid=1074]
–
Tench One workaround might be to write a simple batch file to run the program then shut down the computer.
You can shut down from the command line -- so your script could be fairly simple:
c:\directory\myProgram.exe
C:\WINDOWS\system32\shutdown.exe -s -f -t 0
If you run GPEdit.MSC you can go to Computer Configuration -> Windows Settings -> Scripts, and add startup /shutdown scripts. These can be simple batch files, or even full blown EXEs. Also you can adjust user configurations for logon and logoff scripts in this same tool. This tool is not available in WIndows XP Home.
The Group Policy editor is not mentioned in the post above. I have used GPedit quite a few times to perform a task on bootup or shutdown. Here are Microsoft's instructions on how to access and maneuver GPedit.
How To Use the Group Policy Editor to Manage Local Computer Policy in Windows XP
What I can suggest doing is creating a shortcut to the .bat file (for example on your desktop) and a when you want to shut down your computer (and run the .bat file) click on the shortcut you created. After doing this, edit the .bat file and add this line of code to the end or where needed:
c:\windows\system32\shutdown -s -f -t 00
What this does it is
- Runs the shutdown process
- Displays a alert
- Forces all running processes to stop
- Executes immediately
I posted this answer too over on superuser.
To do this you will need to set up a custom event filter in Task Scheduler.
Triggers > New > Custom > Edit Event > XML
and paste the following:
<QueryList>
<Query Id="0" Path="System">
<Select Path="System">
*[System[Provider[@Name='User32'] and (Level=4 or Level=0) and (EventID=1074)]]
and
*[EventData[Data[@Name='param5'] and (Data='power off')]]
</Select>
</Query>
</QueryList>
This will filter out the power off event only.
If you look in the event viewer you can see under Windows Logs > System under Details tab>XML View that there's this.
- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
<Provider Name="User32" Guid="{xxxxx-xxxxxxxxxxx-xxxxxxxxxxxxxx-x-x}" EventSourceName="User32" />
<EventID Qualifiers="32768">1074</EventID>
<Version>0</Version>
<Level>4</Level>
<Task>0</Task>
<Opcode>0</Opcode>
<Keywords>0x8080000000000000</Keywords>
<TimeCreated SystemTime="2021-01-19T18:23:32.6133523Z" />
<EventRecordID>26696</EventRecordID>
<Correlation />
<Execution ProcessID="1056" ThreadID="11288" />
<Channel>System</Channel>
<Computer>DESKTOP-REDACTED</Computer>
<Security UserID="x-x-x-xx-xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxxx-xxxx" />
</System>
- <EventData>
<Data Name="param1">Explorer.EXE</Data>
<Data Name="param2">DESKTOP-REDACTED</Data>
<Data Name="param3">Other (Unplanned)</Data>
<Data Name="param4">0x0</Data>
<Data Name="param5">power off</Data>
<Data Name="param6" />
<Data Name="param7">DESKTOP-REDACTED\username</Data>
</EventData>
</Event>
You can test the query with the query list code above in the event viewer by clicking
Create Custom View... > XML > Edit query manually
and pasting the code, giving it a name Power Off Events Only before you try it in the Task Scheduler.
You can run a batch file that calls your program, check out the discussion here for how to do it: http://www.pcworld.com/article/115628/windows_tips_make_windows_start_and_stop_the_way_you_want.html
(from google search: windows schedule task run at shut down)
On Windows 10 Pro, the batch file can be registered; the workaround of registering cmd.exe and specifying the bat file as a param isn't needed. I just did this, registering both a shutdown script and a startup (boot) script, and it worked.
I had to also enable "Specify maximum wait time for group policy scripts" and "Display instructions in shutdown scripts as they run" to make it work for me as I explain here.
This is tested on Windows7
(i) For easier code reading, use an IDE or even an 'advanced Notepad'. I use 'Notepad3'.
How to schedule a task to run when shutting down windows?
In short: Make a Windows "Scheduled Task" and connect it with batch||program||executable.
That's how to do:
:: To make scheduled task: (manually)
::
:: Open Task Scheduler (taskschd.msc)
:: Task Scheduler Library > (R-Click) "Create New Task..."
:: Create Task
::
:: General(tab)
:: Name: Shutdown-Hibernate_If_Idle
:: Description: Shutdown or Hibernate if prolonged CPU idle time.
:: CHECK: Run with highest privileges
:: Triggers(tab) > New...(button)
:: Begin the task: On idle
:: CHECK: Enabled
:: Actions(tab) > New...(button)
:: Action: Start a program
:: Program/script: Browse... for path/file to be executed.
:: [ie. C:\ShutDownTime.cmd]
:: *This is the batch||executed that will run when
:: meets "Triggers, Actions, Conditions and Settings".
:: Could be also a program (.exe).
:: Conditions(tab)
:: CHECK: Start the task only if the computer is idle for: 10 minutes
:: Wait for idle for: 1 hour (or any duration you like)
:: UNCHECK anything else
:: Settings(tab)
:: CHECK:
:: Allow task to be run on demand
:: Stop the task if it runs longer than: 3 days
:: If the running task does not end when requested, force it to stop
:: If the task is already running, then the following rule applies:
:: Do not start a new instance
:: Press OK
:: Done!
Note 1: Can be also make a scheduled task from cmd||powershell.
Note 2: Can be also import||export an .xml file to||from scheduled task.
Shutdown-Hibernate_If_Idle.xml example code:
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2023-05-11T20:23:31.9121806</Date>
<Author>%USERDOMAIN%\%USERNAME%</Author>
<Description>Shutdown or Hibernate if prolonged CPU idle time.</Description>
</RegistrationInfo>
<Triggers>
<IdleTrigger>
<Enabled>true</Enabled>
</IdleTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>%USERDOMAIN%\%USERNAME%</UserId>
<LogonType>InteractiveToken</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>false</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<Duration>PT10M</Duration>
<WaitTimeout>PT1H</WaitTimeout>
<StopOnIdleEnd>false</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>true</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>P3D</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>C:\ShutDownTime.cmd</Command>
</Exec>
</Actions>
</Task>
Note1: If Laptop used, set proper settings for battery.
Note2: Must already configured and enabled "power plan" from Control Panel > Power Options > Edit Plan Settings > Change advanced power settings. If Hibernate don't show up in Advanced settings under '[+] Sleep', use command prompt: 'POWERCFG -H ON'. (powerful command! use help powercfg /? to check)
As an example, that's my batch: (Note: there are many 'things' can be excluded from batch, as those are ie. notes||comments or formations for output||display||etc.)
ShutDownTime.cmd example code:
:: This command batch is intended for an (already regulated: "Shutdown if idle")
:: "Windows Scheduled Task" which automatically runs this batch in case of prolonged
:: CPU idle time. (by adonios77)
@echo off
::PROMPT $_
TITLE ShutDown/Hibernate (for scheduled task)
mode con: cols=58 lines=16
color 4F
CLS
SETLOCAL EnableExtensions EnableDelayedExpansion
@echo () &&color f4 &&timeout /t 1 >nul &&color 4f
:__________________SHORTCUTS LOCATIONS
::_Ghostbuster.exe (path\)
SET "_GhostbusterPathExe=C:\Portables (programs)\GhostbusterLatest"
::_Ghostbuster.INI file (path\+ini)
SET "_GhostbusterINI=%APPDATA%\Ghostbuster\Ghostbuster.ini"
:: depended on different versions :: "%APPDATA%\WaitCursor\WaitCursor.ini"
:: Note: %APPDATA% = C:\Users\%USERNAME%\AppData\Roaming
:____________________Removing Ghost Devices
echo Cleaning ...
echo removing "ghosted" Devices ...
:GhostBuster
START /REALTIME /WAIT /d "%_GhostbusterPathExe%" Ghostbuster.exe /nogui "%_GhostbusterINI%" && ^
echo Ok, Ghostbuster is finnished.
echo:
:____________________TIMEOUT warning
@echo () &&color f4 &&timeout /t 1 >nul &&color 4f
::echo 60sec delay...
::echo 30 sec timeout ... && timeout /t 30
::taskkill /im "waterfox.exe" /t /f
:__________________HIBERNATE
echo Going to Hibernation ...
echo *default auto-selected [2] after 60sec ...
echo:
choice /c 012 /n /t 60 /d 2 /m "Press[#]: [0]Cancel, [1]Shutdown, [2]Hibernate ?"
IF %ERRORLEVEL% EQU 1 exit
IF %ERRORLEVEL% EQU 2 goto :__________________SHUTDOWN
IF %ERRORLEVEL% EQU 3 shutdown /H /f
EXIT
:__________________SHUTDOWN
echo:
echo Shuting Down NOW ...
echo:
chkntfs /x c:
CD %windir%\system32
SHUTDOWN.exe /s /t 60 /f /c "PC shutting down... (in 1 minute)"
echo Press any key to CANCEL Shutdown . . .
pause >NUL
shutdown /a
::SHUTDOWN.exe /s /t 60 /f /d p:0:0 /c "PC shutting down... (in 1 minute)"
Note 1: What follows the "::
" double semicolons are just Comments that not affects batch.
Note 2: At the lines "@echo ( )
...", into parenthesis there is one or more "Alt+NumPad007" "BEL symbol" that makes PC beep sound(s). Here it doesn't showed up.
© 2022 - 2024 — McMap. All rights reserved.
C:\Windows\System32\cmd.exe
as the Script Name and/C C:\path\to\batch\script.bat
as the Script Parameters, it did. – Lentiginous