Keeping disks defragmented
I want to keep my disks defragmented, with these constraints:
· Don’t consume the disk IO resources while I’m working
· Don’t make me remember to launch defrag before I go home
· Defrag all my disks, not just one (Windows defragger only does one at a time)
· Work correctly even if I run as normal user
To support this, I wrote a small script to run the defragger. Here it is:
@if "%_Echo%" == "" echo off
if "%1" == "" goto Usage
:next
cd /d %1\
echo defragmenting %1 > defrag.log
defrag -v -f %1 >> defrag.log 2>&1
shift
if NOT (%1) == () goto next
goto :EOF
:Usage
echo pass volumes on the command line:
echo.
echo %~n0 c: d: c:\mount_point
goto :EOF
I’m known for writing confusing batch files, so let’s go through it:
@if "%_Echo%" == "" echo off
Turn off echo by default. If you want to see echo output, ‘set _echo=1’.
cd /d %1\
The ‘/d’ option means change the current drive, too. (Should be the default, but hard to change now.)
defrag -v -f %1 >> defrag.log 2>&1
Run the defragger. ‘-v’ means generate verbose output about the number of fragmented files before & after, etc. Redirect it all to defrag.log, which will be (normally) be written to the root of the drive.
shift
if NOT (%1) == () goto next
Repeat for each parameter.
goto :EOF
exit the batch script. (If you use ‘call :label’ then just exit this instance).
echo %~n0 c: d: c:\mount_point
%~n0 means ‘just the base name of the current batch file’.
Next, add a scheduled task:
Control Panel -> Scheduled Tasks
File->New->Scheduled Task (Don’t use the Add Scheduled Task wizard)
Give it a name (“defrag”).
RClick, Properties:
- Set the schedule as it suits you. I told it to abort my job after 1 hour, just in case something is really broken.
- OK. You’ll be prompted for local admin credentials
Now you’ll have a new task in the scheduled tasks list. Time to verify it.
RClick on the task, Run
Watch its ‘Status’ change. You want it to say ‘Running’ for at least a minute. Anything else & something is broken. Take a look at Advanced->ViewLog for clues.
The first time this ran, it was aborted after an hour. The next night it ran again & completed. I think I’ll leave it like that.