Windows Server

Defragment your Windows Server 2003 hard drive on a set schedule

You can defragment the hard drives on your Windows Server 2003 boxes on a set schedule by simply creating a batch file to defragment a drive and setting up a scheduled task to execute it.

You can defragment the hard drives on your Windows Server 2003 boxes on a set schedule by simply creating a batch file to defragment a drive and setting up a scheduled task to execute it.

Creating a .bat file

To create this little piece of code, open a new file in your favorite text editor, such as Notepad. You will also need to open the Windows command shell (cmd.exe). The command shell will help you nail the syntax of the operation so there are as few hiccups as possible.

  1. In the command prompt window, enter the following:

    C:> defrag.exe /?

    The help documentation will display for defrag.exe, showing the syntax you need to run the application and any optional switches.
  2. To keep it simple and to restrict the defrag operation to one drive, you can enter the syntax for our batch file into the text editor as follows: Defrag.exe c: -f
  3. Save the text file with a name and the .bat file extension.
  4. You will also select all files in the file types drop down.

Scheduling the execution of fragments To schedule the batch file to run, we can run an AT command from the command prompt. AT commands add Scheduled Tasks without going through the GUI-based application; this can speed up the creation of scheduled tasks. For more information about AT commands, read the TechRepublic article, "Buy some time by automatically scheduling administration chores."

In the command prompt window, press [Enter] a few times to get a C:\> prompt within view. Enter the following to see the syntax and examples of the AT command:

AT 02:30am /every:M,T,W,Th,F c:\defragment.bat

Note: Walking through the entire process will help to familiarize you with all of the available options for commands used in this tip. The help display is for demonstration purposes only; you do not need to perform it.

Press [Enter] after entering the command, and a scheduled defragmentation of the local C: drive will take place weekdays at 2:30 in the morning.

You can verify the task by visiting the Scheduled Tasks folder in the Accessories folder of the Start menu.

Miss a column?

Check out the Windows Server 2003 archive, and catch up on the most recent tips from this newsletter.

Stay on top of the latest Windows Server 2003 tips and tricks with our free Windows Server 2003 newsletter, delivered each Wednesday. Automatically sign up today!

About

Derek Schauland has been tinkering with Windows systems since 1997. He has supported Windows NT 4, worked phone support for an ISP, and is currently the IT Manager for a manufacturing company in Wisconsin.

31 comments
acropolister
acropolister

Whether automatically or manually, it is important to track fragmentation levels and combat this insidiuous disease as it arises. Otherwise, it has the potential to bring a high traffic, critical server down to it's knees. These things are well known to people in the IT field, but are worth repeating for the benefit of other readers.

sancretor
sancretor

Why bother with batch files and/or manual defrags? Both are rather outdated approaches to looking at the defrag problem. Instead of being stuck in the past, we ought to be looking towards the future - a system maintenance regimen that is automatic and intelligent i.e. capable of monitoring for trouble and launching itself as necessary, and with reliability. An "always-ON", intelligent automatic defragmentation solution which does not rely on human supervision is far more attractive in terms of admin workload and output since it involves less labor/manpower (lower costs!!) and the defragmentation benefit is continuous. It's a no-brainer.

shellie.luallin
shellie.luallin

Some limits on simply running command line defrag: There should be a minimum of 15% free space per drive. Do not run it on a server running Exchange server. Check cluster size - if less than 4 KB and you have VSS (volume shadow copy) applications active you'll have problems. Why isn't this built in? I'm sure it has to do with an agreement... Check: http://support.microsoft.com/kb/130539 The summary states: Microsoft Windows Server 2003, Microsoft Windows XP, and Microsoft Windows 2000 include a tool for disk defragmentation. The Windows Disk Defragmenter tool is a limited version of the Diskeeper program from Diskeeper Corporation. Disk Defragmenter does not include all the features available in the full version of Diskeeper.

pete.lee
pete.lee

Why don't you just used Diskeeper 2007. It does a fantastic job of Defragging your drive it doesn't need to be scheduled as it only defrags when the system is not busy. It also defrags you MFT. The cost of diskeeper is is cheap.

mail2rafeek
mail2rafeek

Hello Sir, thank you very much for your tips. i thought this will reduce IT peoples work load. it's great. also one request for you. how can i disable the scheduled De-fragment task? Thank you. Rafeek

unixwolf.edu
unixwolf.edu

Does this work on a RAID also? IF the OS is installed on a RAID and/or a RAID is attached.

Senior Program Analyst
Senior Program Analyst

Why doesnt Windows have defragmentation built directly into thier operating system by now. Just have a background defragmentation run and have it set for anytime Disk and CPU usages are below say 10% at the same time. That way it will always remain defragmented. Or have the disk drives contain the ability to move files as needed to store only in contiguous method (dont allow fragmentation in the first place). Cant believe that there isnt a better solution these days built right in.

john.duncan
john.duncan

This is a good start, but I need to defrag C, D, and E and I need to have a record of it, a text file would be fine. Can you adjust your batch file?

michael.stretz
michael.stretz

Good article, but if you have to be told every little step, then keep your hands off the server. Here's the short version: Create a batch file called c:\defrag_c.bat. In it, have the following command: Defrag.exe c: -f (or whatever switches you need) In the command prompt, type AT 02:30am /every:M,T,W,Th,F c:\defrag_c.bat (Type AT /? for more switch options.) You can verify the task by visiting the Scheduled Tasks folder.

luis.christopher
luis.christopher

When setting up the schedule task using the GUI, you are prompted to enter a ID/Passwd to use to run the task. Use a Service account that has admin priviliges(if one exist).

b_caisse
b_caisse

@echo off set logpath=c:\scripts\logs set my-email-address=YOUREMAIL@YOURDOMAIN.COM set SMTP=mail.YOURMAILSERVER.COM rem echo %date% %time% >"%logpath%\defrag.log" echo =================================================== >>"%logpath%\defrag.log" echo START DEFRAG of drive C echo --------------------------------------------------- >>"%logpath%\defrag.log" defrag c: -f -v >>"%logpath%\defrag.log" echo END DEFRAG of drive C echo =================================================== >>"%logpath%\defrag.log" echo %date% %time% >>"%logpath%\defrag.log" rem rem Blat - A Win32 command line SMTP mailer. rem Use it to automatically eMail logs, rem the contents of a html FORM, rem or whatever else you need to send. rem blat /? for help rem rem http://sourceforge.net/projects/blat/ rem blat "%logpath%\defrag.log" -serverSMTP %SMTP% -to %my-email-address%

gijojohnso
gijojohnso

what is defragment mean what excatly that thing do in the computer

RoyB
RoyB

I guess if you log onto a server, your account has permissions to defrag the drives. What about after the admin logs out, what permissions are used to make this still work?

TonytheTiger
TonytheTiger

You're adding a record to a 30 gigabyte database. Its current physical location is flanked by two other 30 gig databases with no space in between. Is the operating system supposed to rewrite the entire database whenever anyone adds a record? Suppose you have a dozen people adding records to 4 different large databases? Are all these rewrite operations supposed to happen at once? With nobody noticing? We've got a long, long way to go.

bullitch
bullitch

Go to control panel, select scheduled task and choose the task you want to delete. I hope it helps.

TonytheTiger
TonytheTiger

We have a server with 900 gig about 40% used. We've never defragged it in the three years we've had it, and out of 1.2 million files, fewer than 50,000 were fragmented. Windows does "try" to not fragment files. When you copy a single file to an NTFS drive, Windows will use a contiguous space to store the file [b]if possible[/b]. Problems arise when either two people are writing files at the same time, or when you are appending an already existing file (databases are an example). It would be grossly inefficient, for example to re-write an entire database to a contiguous area of the disk every time a user added a record! Also you usually cannot defrag a file while it is open for write, so I'm not sure how well a resident defrag would run on a server. Finally, I don't know how fragmentation affects Raid-5 drives common on servers. Contiguous logical clusters (or groups of them) are on different physical drives anyway, so I wonder how much performance you'd actually gain by defragging a Raid-5 volume.

System007
System007

One of the reasons Microsoft doesn't bundle more robust apps with the OS is so they (Microsoft) don't end up stepping on third-party developer's feet. If Microsoft included a robust defragmentation app in Windows OSs, for many people, it would remove the need to seek better solutions from third parties, and potentially kill third party apps such as Diskeeper and PerfectDisk. Deciding how far to go with a bundled app is a delicate balancing act.

bcgreaves
bcgreaves

THAT would be excellent! Especially for large hard drives that have files put on and pulled a lot. Good Point!

Derek Schauland
Derek Schauland

You can write the output of the defrag.exe action to a text file using the following: defrag.exe c: -a -v > result.txt the -v is for verbose output which is recoreded then in result.txt. the -a added here is for analyze only, used here to speed up the process to results. To defrag, leave the -a out of the command To handle multiple drives, I would create a separate batch file for each drive as only one drive at a time is supported. You can schedule them back to back and have the results of each written to its own text file. Should get you the results you need

babajideibiayo
babajideibiayo

Yeah that script was a real blast!!!! Any ideas for great scripts for patch management? BR

bullitch
bullitch

I hope those previous postings help you understand what defragmentation means. If not, Google it.

Senior Program Analyst
Senior Program Analyst

Simply it rearranges the files on your disk to make sure all files are in as few pieces as possible. The more you delete and save files the more times a file cant fit into a free area of the disk and windows breaks it up into pieces so it will fit into the holes. Might go to Google Search and search on "What does Defragmenting do" will bring up several different documents explaining further.

DigiTechDude
DigiTechDude

In this modern day and age why use a batch file? I wrote a VBS script that is pretty universal. It scans for any local fixed disks, defrags them, and writes a success/failure report to the application event log. Runs entirely in background and invisible. Easy to implement on servers and push to all clients through Group Policy. Microsoft did release defrag in 2003 server environment, you just have to write a script to do it. I like it better that way actually as you can make it do wahtever you want, however you want. Some people might just want a basic defrag others, like myself, may want to advanced options to scan for local drives and logging. Once you have the script how you want it there's no config for individual machines.

Derek Schauland
Derek Schauland

When scheduling the job to run as a task you can specify administrator credentials to allow the task to be executed after hours without requiring a logon.

sancretor
sancretor

Not necessarily defrag in 'real-time' though it would be great, but atleast when there are sufficient free resources to automatically defrag whenever there is a chance, without affecting server performance and without having to take the servers offline too often. (apologies for the run-on sentence). The thing is, automatic defraggers are *already in use* on servers. Is the technology absolutely perfect already? I don't know the answer to that, but it is definitely heading in the right direction. As the number of machines (servers + workstations) usually grow every year, system maintenance will also grow more expensive in terms of manpower and time. That's why I feel that automation is the best route.

bullitch
bullitch

Sir where can i find the log file of the script? I downloaded the script and used it already but i wonder where the created log file will be stored. Thanks.

bcgreaves
bcgreaves

I saved your script to my HD but have absolutely no idea what to do with it. I'm a GUI guy and just don't know enough about how things are written, would you help me as to what to do with this file and how to use it in GP please? I would appreciate it.

mldennis
mldennis

We have been needing something like this and would love to be able to use it. michael.dennis@"nospam"colostate.edu Thanks. --M

tcunningham4
tcunningham4

There is no GUI version of the script, but you can schedule it via gui -- go to Control Paanel -> Scheduled Tasks and add a new task. Specify the batch file as the program to run and setup the schedule as needed. Once a week is probably sufficient for a defragmentation, but you may want to stagger it over several days if you have more than one drive to do. This will even work for external USB or Firewire drives, but they need to be the same drive lettert unplug the drives, or you will have to update the batch program. You won't have to reschedule just for modifiatinos to the batch file. To thest the batch program gfunchtion, just double-click it. to test the scheduletr function, you can right-click on the entry in task scheduler and select run now. Good luck !!!

mldennis
mldennis

I will let you know if we come up with any enhancements.