scatterbits
scatterbits

Reputation: 331

Execute batch file every X runs

I have a batch file I want to run at Windows shutdown (executed via GPO shutdown script) but I only want it to run after a certain number of system shutdowns, not at every shutdown. This is because what it does causes a delay in the shutdown process and I want to reduce disruption.

The only thing I can think about is to construct some logic that checks how many times the computer was shut down and after the defined threshold is crossed the batch file is executed, but would anyone have an example of how to do this? I searched but only found examples of how to run a script every x periods or times, not every x runs.

Thanks in advance!

Upvotes: 2

Views: 706

Answers (2)

dbenham
dbenham

Reputation: 130849

You could call your batch file upon every shutdown, and include the following at the top to abort if the shutdown threshold has not been met.

@echo off

::Test if the shutdown threshold has been met. Exit if it hasn't
setlocal
set /a "threshold=5, cnt=1"
set shutdownCountFile="C:\SomePath\shutdownCount.txt"
if exist %shutdownCountFile% for /f "usebackq" %%A in (%shutdownCountFile%) do set /a cnt=%%A+1
if %cnt% geq %threshold% (
  2>nul del %shutdownCountFile%
  endlocal
) else (
  >%shutdownCountFile% echo %cnt%
  exit /b
)

:: Your batch process goes here

You could also use a registry entry to keep track of the number of shutdowns instead of a file.

Upvotes: 1

kbulgrien
kbulgrien

Reputation: 4508

@ECHO OFF
SET LIMIT=4
SET SAVEFILE="COUNT.TXT"
SETLOCAL ENABLEDELAYEDEXPANSION

REM Get the current count or start a new file if it does not exist.
IF EXIST %SAVEFILE% GOTO READFILE
ECHO 0 >%SAVEFILE%
:READFILE
SET /P COUNT= <%SAVEFILE%

REM Increment the save file value by one.
FOR %%B IN ( "%SAVEFILE%" ) DO (
  CALL :ADD_ONE
)
ECHO %COUNT% >%SAVEFILE%
GOTO CHECK_VALUE
:ADD_ONE
SET /A COUNT+=1
GOTO :EOF

REM Conditionally reset the counter and do something.
:CHECK_VALUE
IF %COUNT% LSS %LIMIT% EXIT /B
DEL %SAVEFILE% 2>NUL

ECHO Do your stuff here...

Upvotes: 1

Related Questions