Batch File to Automate Basic Disk Check and Defrag in Windows
Posted on : 12-04-2009 | By : Vishal Vasu | In : General, Windows Server
Tags: windows 2003
1
Since I maintain and administer lot of Windows and Exchange Servers, running basic disk checks and defrag on the servers manually is simply impossible. To achieve the goal, I had a small batch file written which automates this task for me.
To start with, create a folder on the machine that you want to automate this on. I named my folder as “MaintenanceScripts”. The next step was to write the batch file with the content given below and save it as “ChecknDefrag.bat”.
@Echo Off REM *************************************************************************** REM * * REM * AUTOMATED DISK CHECK AND DEFRAGMENTATION SCRIPT * REM * * REM ***************************************************************************
REM chkdsk and defrag automation REM Read the Drive Letter from the file for /F "eol= tokens=1 delims=( " %%i in (DriveLetter.txt) do set DrvLtr=%%i& call :dsKchk
:dsKchk If %DrvLtr% == end goto :eof echo. >> diskcheck.rtf echo. >> diskcheck.rtf echo ******************************************************** >> diskcheck.rtf echo CHECK DATE and TIME for %DrvLtr% >> diskcheck.rtf date /t >> diskcheck.rtf time /t >> diskcheck.rtf echo ******************************************************** >> diskcheck.rtf echo. >> diskcheck.rtf echo. >> diskcheck.rtf echo RUNNING DISK CHECK ON %DrvLtr% .... chkdsk %DrvLtr% >> diskcheck.rtf goto :defrag
:defrag echo. >> defrag.rtf echo. >> defrag.rtf echo ******************************************************** >> defrag.rtf echo CHECK DATE and TIME for %DrvLtr% >> defrag.rtf date /t >> defrag.rtf time /t >> defrag.rtf echo ******************************************************** >> defrag.rtf echo. >> defrag.rtf echo. >> defrag.rtf echo RUNNING DISK DEFRAGMENTATION ON %DrvLtr% .... defrag %DrvLtr% -b >> defrag.rtf defrag %DrvLtr% -f >> defrag.rtf :EOF
The above batch file checks for a file called “DriveLetter.txt” in the same folder from where the script it going to run from. You can change it to your liking. It also saves the report of the disk check to a file called “diskcheck.rtf” and for defrag to a file called “defrag.rtf”. I choose RTF so that I can open it in MS Word or any other application to see a nice formatted output.
Next, we create a file called “DriveLetter.txt” in the same folder where we saved the Batch File and add all the drive letters that we want the script to check:
C: end
You can add more disks to the above file by writing the drive letters to the text file – one drive per line.
Run the batch file once and wait for it to finish. Once it finishes its run, you can open the RTF files and see the results. If you are satisfied that everything is working fine with the batch files, you can now move towards scheduling the batch file to run at off-peak hours.



















