1

I have a batch script that I want to run every time the system restarts.

Currently, I placed the batch script in

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp

But that does not serves the purpose as it will start the script even in case of boot up.

So, I am looking for a way to run the script only in case of system restart.

1
  • There isn’t a difference between a restart and a cold boot from the perspective of what happens when a user logs into their account. If you want to run a script when the system is going to reboot you will have to do that as it’s being rebooted through a scheduled event
    – Ramhound
    Commented Sep 18, 2020 at 9:53

1 Answer 1

0

Windows generate event logs in System log with event ID 1074 after each shutdown/restart/power off.

So, we can use A simple command to determine if the last shutdown was actually a shutdown or restart:

for /f "tokens=3 delims=: " %%a in ('wevtutil qe system "/q:*[System [(EventID=1074)]]" /rd:true /f:text /c:1 ^| find /i "Shutdown type:"') do if "%%~a"=="restart" (echo System has done a restart)

Then we can first create a batch file, that will launch your batch file, only in case of system restart. (Set the value of %BatchFile% to the path of your batch file)

@echo off
::!!!ATTENTION!!!
set "BatchFile=BATCH FILE PATH HERE"
for /f "tokens=3 delims=: " %%a in ('wevtutil qe system "/q:*[System [(EventID=1074)]]" /rd:true /f:text /c:1 ^| find /i "Shutdown type:"') do if "%%~a"=="restart" (start "" "%BatchFile%")

And this one will add itself to startup, to check if system has initiated from a reboot, and then execute main file, otherwise do nothing:

@echo off
::!!!ATTENTION!!!
set "BatchFile=BATCH FILE PATH HERE"
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v "RebootChecker" /d "cmd.exe /c "%0"" /f 
for /f "tokens=3 delims=: " %%a in ('wevtutil qe system "/q:*[System [(EventID=1074)]]" /rd:true /f:text /c:1 ^| find /i "Shutdown type:"') do if "%%~a"=="restart" (start "" "%BatchFile%")

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .