2012-08-28 37 views
2

我有一個批處理文件,我想在Windows關機時運行(通過GPO關閉腳本執行),但我只希望它在一定數量的系統關閉後運行,而不是在每次關閉時運行。這是因爲它會導致關機過程中的延遲,並希望減少中斷。每X次運行執行批處理文件

我可以考慮的唯一的事情是構建一些邏輯來檢查計算機關閉了多少次,並且在超過定義的閾值後批處理文件被執行,但是誰會有一個例子來說明如何做到這一點?我搜索,但只發現如何運行一個腳本每x個週期或時間,而不是每個x運行的例子。

在此先感謝!

+0

使用存儲在文件中的計數器,然後在每次運行批處理文件時讀取並更新它。 – Jay

回答

1
@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... 
+0

再次感謝 - 將檢查並回報! – scatterbits

+0

非常感謝你的創作! – scatterbits

1

您可以在每次關機時調用您的批處理文件,並在關閉閾值未滿足時在頂部包含以下內容以中止。

@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 

您還可以使用註冊表項來跟蹤關閉的數量而不是文件。

+0

這看起來不錯!非常感謝您的回覆 - 非常感謝:)將盡快測試並報告;) – scatterbits

+0

Windows XP - >「usebackq」此時出乎意料。 – kbulgrien

+0

好的,我測試了這個,我想我不明白什麼需要在shutdownCount.txt文件中?這就是我得到: C:\用戶\埃雷茲\桌面> 1.BAT C:\用戶\埃雷茲\桌面> SETLOCAL C:\用戶\埃雷茲\桌面>設置/「門檻= 5,cnt = 1「 C:\ Users \ Erez \ Desktop> set shutdownCountFile =」C:\ Users \ Erez \ Desktop \ shutdownCount.txt「 」usebackq「此時意外。 (「C:\ Users \ Erez \ Desktop \ shutdownCount.txt」)中的%F「usebackq」%A的C:\ Users \ Erez \ Desktop> do set/a cnt =%A + 1 C: \ Users \ Erez \ Desktop> – scatterbits