I’d like to automatically defragment my hard disk periodically so I just
don’t have to worry about it any more. I’ve heard of the Windows Task
Scheduler, can I use that?
Yes you can. In fact, I do.
OK, I run a lot of things in the middle of the night, but periodic
defragging is one of them.
Let’s walk through the steps.
Become a Patron of Ask Leo! and go ad-free!
We’ll set up the command line version of the defragmenting tool
defrag.exe to run once a week. I’ll arbitrarily pick 3 AM on
Sunday mornings, but you can naturally set your own schedule.
Starting in Control Panel, double click on
Scheduled Tasks. Then double click on Add a Scheduled
Click Next. You’ll be presented with this list of programs
to choose from:
Unfortunately the tool we want, defrag.exe, isn’t on that list. Click on
Browse and you’ll find defrag.exe at
C:\Windows\System32\defrag.exe. Click Open.
Next, you’ll need to give the task a name and begin choosing the schedule:
You can choose a different name for the task if you like. Click on
Weekly and then click Next:
As I indicated, I’ve selected 3AM every Sunday. Click
Next. Each scheduled task is run as if it were a separate login to your machine,
so at this point you’ll need to enter a login account and password that the
system should use to run the task.
And you’re done! Click Finish, and the task will now run
automatically every Sunday at 3AM.
Now, there’s a problem with what we’ve done so far: there’s no log of the
results. Defrag might run, but any messages it might output are lost.
Unfortunately there’s no built-in solution, but that doesn’t stop us.
The approach I take is fairly simple. First, use notepad to create a command
file containing this single line:
Save that as c:\windows\loggeddefrag.cmd.
That command file runs defrag.exe and saves all normal and error output to
the file “c:\defrag.log”. Try it. You can run “loggeddefrag”
in a Windows Command Prompt, and when it completes you can have a look a the
log it creates.
Now we just need to update our scheduled task.
Once again in Control Panel, double click on
Scheduled Tasks. This time right-click on the task we created:
“defrag“, and click on Properties:
Now simply change the C:\WINDOWS\SYSTEM32\defrag.exe to the
command file we just created: c:\windows\loggeddefrag.cmd:
Press OK, and you’ll have to re-enter the password for the
account that will be used to run the scheduled task.
Now you’re really done. Check that log file each Sunday morning and you’ll
see that the defragmenter has run as well as any errors it might have encountered
along the way.