How to schedule a task to run when shutting down windows
Asked Answered
C

12

96

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.

Crepuscular answered 19/9, 2008 at 13:0 Comment(0)
K
106

Execute gpedit.msc (local Policies)

Computer Configuration -> Windows settings -> Scripts -> Shutdown -> Properties -> Add

Kettle answered 19/9, 2008 at 13:5 Comment(7)
If you want a batch script to run at Logoff, I found referencing the .bat file directly didn't work. However, if I used C:\Windows\System32\cmd.exe as the Script Name and /C C:\path\to\batch\script.bat as the Script Parameters, it did.Lentiginous
WARINING: The group policy startup and shutdown scipts not executed, when using fastboot (enabled by default in windows 8 and up). In this case, only the restart or force shutdown (from command prompt) shut down really the computer. In all other cases (start menu shutdown), the computer kernel hibernated, and revieved on boot, and GPO startup and shutdown scipts are ignored.Very
@voji: Is this true for Windows Server as well?Maryjanemaryjo
how about restart?Trying
these don't seem to run at all on Server Core 1909Errantry
Under which security context/user are those shutdown scripts executed? Something like 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
fyi default timeout is 10min based on MaxGPOScriptWaitCerellia
C
47

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:

  1. Run gpedit.msc (Local Policies)
  2. Computer Configuration -> Windows Settings -> Scripts -> Startup or Shutdown -> Properties -> Add

For Logon/Logoff:

  1. Run gpedit.msc (Local Policies)
  2. User Configuration -> Windows Settings -> Scripts -> Logon or Logoff -> Properties -> Add

Source: http://technet.microsoft.com/en-us/library/cc739591(WS.10).aspx

Caterpillar answered 11/9, 2013 at 17:25 Comment(2)
This is the better answer. When you open GPEditor it shows two nodes as you describe. Since both nodes have a Windows Settings option then the accepted answer is less clear than your answer. Thanks for the tip. Very helpful.Photodrama
But does a shutdown also count as a logoff (and run the logoff scripts)?Margarite
F
42

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.

Falsehood answered 6/12, 2014 at 1:59 Comment(7)
Thanks for the tip! @Oz, Will this run on restart as well as shutdown? The case I'm trying to cover is Windows Update forces a restart...Slide
Yes, it is, since this event is logged on restart / shutdown.Falsehood
Please note, that the argument /ec system does not exist, but it is called /ru system. see support.microsoft.com/en-us/kb/814596#bookmark-4Alissaalistair
@t2d, while /ec exists in newer versions, /ru refers to a completely different thing. EC allows you to specify an event channel, while ru allows you to run as another user. Nonetheless thank you for your comment. I'll edit my post accordingly.Falsehood
For LogOff, Source is WinLogon and EventID is 7002Agra
There's a typo in the modifier in your example. It should be ... /mo *[system/eventid=1074], not .../mo *[system/evendid=1074]Tench
On Windows Server 2019, in Azure VMs, this doesn't appear to work. My script never gets executed and Task Scheduler shows it failed because a shutdown was in progress.Erie
S
6

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
Squama answered 19/9, 2008 at 13:6 Comment(0)
P
5

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.

Pudency answered 19/9, 2008 at 13:7 Comment(0)
R
5

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

Resile answered 19/9, 2008 at 13:9 Comment(0)
B
3

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

  1. Runs the shutdown process
  2. Displays a alert
  3. Forces all running processes to stop
  4. Executes immediately
Binnacle answered 19/8, 2017 at 11:0 Comment(0)
N
3

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.

Nikkinikkie answered 31/1, 2021 at 21:23 Comment(0)
T
1

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)

Tapis answered 19/9, 2008 at 13:4 Comment(0)
B
1

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.

Birdt answered 5/11, 2018 at 3:54 Comment(0)
M
0

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.

Mickel answered 13/8, 2019 at 6:25 Comment(0)
D
0

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.

Drabble answered 12/5, 2023 at 12:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.