Defrag SQL MDF and LDF on Server

I wrote this script to defrag all the found MDF and LDF files on a server that I’ve been testing on.  It uses Sysinternal’s Contig tool which is a single-file defrag tool.

@echo off
: Rich Kreider
:
: You need contig.exe from sysinternals:  http://live.sysinternals.com/contig.exe
SETLOCAL
set MINFRAGMENTS=5
set CONTIGBIN=c:tempcontig.exe
if not exist %CONTIGBIN% goto missingcontig
: Don't play with this...
set TOTALMDF=0
set TOTALLDF=0
set FRAGCOUNT=0
FOR %%P IN (C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO (
  IF EXIST %%P:nul (
 call :checkdrive %%P
  )
)
: set __NeedsDefrag
for /f %%x in ('set __NeedsDefrag 2^>NUL ^|find /v /c ~~~') do (
if %%x geq 1 (
echo *** FOUND FILES NEEDIN DEFRAGMENTATION ***
for /f tokens=2* delims=|= %%A in ('set __NeedsDefrag') do (
echo Defrag: %%A = %%B
)
call :ask
)
)
goto eof
:checkdrive
for %%y in (mdf ldf) do (
echo ===Searching %%P:*.%%y...
for /F delims=, %%x in ('dir /b /s %1:*.%%y 2^>NUL') do (
 if exist %%~fsx (
 if %%y==mdf set /A TOTALMDF+=1
 if %%y==ldf set /A TOTALLDF+=1
 call :analyze %%~fsx
 )
)
)
echo ===%1 MDF: %TOTALMDF%  LDF: %TOTALLDF%
goto :eof
:analyze
for /F tokens=2,5 %%i in ('%CONTIGBIN% -a %1 ^| find is in') do (
if %%j geq %MINFRAGMENTS% (
 set __NeedsDefrag^|%1^=%%j frags/file
)
)
goto :eof
:ask
set answer=
set /p answer=Defragment all? (y/n):
if %answer%== goto ask
if /i %answer:~0,1%==y goto defrag
if /i %answer:~0,1%==n goto eof
goto :eof
:defrag
for /f tokens=2* delims=|= %%A in ('set __NeedsDefrag') do (
 echo Starting defrag on %%A...
 %CONTIGBIN% -q %%A 2>NUL 1>NUL
 for /F tokens=2 delims=: %%r in ('%CONTIGBIN% -a %%A ^| find Average') do (
 echo Completed defrag on %%A (Was %%B now %%r^)
 )
 echo.
)
goto :eof
:missingcontig
cls
echo.
echo.
echo. Missing contig binary;  you NEED this.
echo. I can start the download now, it should open
echo. in your default browser.
echo.
echo. After you download it, note the location
echo. and modify this file and set CONTIGBIN accordingly.
echo.
start http://live.sysinternals.com/contig.exe
goto eof
:eof
echo Press any key to quit...
pause >NUL

Published by

Rich

Just another IT guy.

Leave a Reply

Your email address will not be published. Required fields are marked *