Mr. Script

Frag Out!

When it comes to sluggish hard drives, this handy script will help keep you moving.

I’ve been spending a fair chunk of my weekends playing Xbox’s premier game, Halo, when I should be changing the car’s oil or walking the dog. In Halo, whenever one of your Marines throws a fragmentation grenade, he announces it by yelling “Frag out,” thus giving you time to avoid the blast. What better lead for a column in which the featured script is one that defragments your hard drives? Besides, who among us hasn’t been tempted, on occasion, to drop a grenade on a server that’s grinding to a slow crawl due to a fragmented drive?

Pull Pin…Take Cover
A fragmented drive can cause more problems than simply slow read/write performance. For starters, the drive hardware has to work harder to retrieve and write data. In extreme cases, this can shorten the life of your hard drive. Furthermore, fragmented data takes up more drive space due to disk cluster sizes. The larger the drive and the larger each cluster, the more space is wasted. While using NTFS and dynamic disks can mitigate these issues somewhat, there’s still no substitute for keeping fragmented files to a minimum. The following script will defrag every drive on the computer and record the status of each defrag operation in a log file, thus enabling you to take the “frag out.” (See, I told you I’d make the connection!)

<?xml version="1.0" ?>
<package>
<comment>
DefragDrives.wsf
This script runs the command-line DEFRAG utility via the WScript.Shell object on each drive of the local computer
</comment>

<job>
   <runtime>
      <description>

      This script defragments all local drives
      </description>
      <example>

      C:\CScript DefragDrives /LogFile:[path and filename]
      </example>
      <named

      name="LogFile"
      helpstring="The path and filename to write
      the defrag report"
      type="string"
      required="true"
      />
      </runtime>
      <object id=
"objShell" progid="WScript.Shell"/>
      <object id=
"objFSO" progid="Scripting.FileSystemObject"/>
      <script language=
"VBScript">
      <![CDATA[
      Option Explicit Dim colDrives, clsDrive, objFile,
      sLogFile, iReturn
      sLogFile=WScript.Arguments.Named.Item("LogFile")
      Set colDrives = objFSO.Drives

      'Open the log file and enter the date/time
      Set objFile = objFSO.OpenTextFile(sLogFile, 8, True)
      objFile.WriteLine
      objFile.WriteLine Date & " " & Time & vbCRLF
      objFile.Close

      For Each clsDrive in colDrives
         If clsDrive.DriveType = 2 Then '2=Fixed drive
             iReturn = objShell.Run("defrag " & clsDrive
             & " -f", 1, TRUE)

      'Open the file and write the defrag report
      Set objFile = objFSO.OpenTextFile(sLogFile, 8, True)
      Select Case iReturn 'Get the return value
         Case 0
            objFile.WriteLine "Drive " & clsDrive
            & " Successfully defragmented."
         Case 1
            objFile.WriteLine "Drive " & clsDrive
            & " Defrag can celled manually."
         Case 2
            objFile.WriteLine "Drive " & clsDrive
            & " Defrag failed! Command-line error!"
         Case 4
            objFile.WriteLine "Drive " & clsDrive
            & " Defrag Failed! Insufficient memory!"
         Case 6
            objFile.WriteLine "Drive " & clsDrive
            & " Defrag failed! System error!"
         Case 7
            objFile.WriteLine "Drive " & clsDrive
            & " Defrag failed! Insufficient drive space!"
         Case Else
            objFile.WriteLine "Drive " & clsDrive
            & " Defrag failed! Unknown error!"
         End Select
            objFile.Close
         End If
      Next
      ]]>

      </script>
   </job>
</package>

The Select Case section skips a couple of numbers, namely, 3 and 5. These return codes both correspond to “Unknown Errors.” By structuring the Select Case section as we have, these (and any other return codes not already specified) will be picked up by the “Case Else” line, and the script will notify you that it experienced an “Unknown Error.” No need to explicitly check for every possible return code.

Those of you who’ve followed this column for any length of time know that my philosophy is to use the simplest method possible to accomplish the task at hand. In this case, I’m combining the organizational strength of the Windows Script Host with the efficiency of the defrag command-line utility. The result is quite a nice little script that can be scheduled to run overnight on any or all of your servers to keep drive hardware humming and disk performance high.

Because the bulk of the functionality comes from shelling to the command line and running defrag, I chose to only open the log file when I had something to write to it. Ordinarily, I wouldn’t keep opening and closing a file over the course of a script. However, because the defrag operation can take hours for each drive, I didn’t want to leave this file open.

The defrag utility returns a value to the shell object after defragmentation is complete (or fails). I then use a Select Case statement to determine the result of the operation and write the data to the log file. This occurs for every fixed drive connected to the computer—floppies, CD-ROMS, removable drives, network shares and RAM disks are skipped.

To run this script, simply type this at the command line:

Cscript DefragDrives.wsf /LogFile:c:\logfilename.txt

Over the next few months, I’m going to feature scripts that were created as a direct result of e-mails I’ve received from readers asking me to show them how to accomplish a specific task. Most of the topics will be based upon those e-mails, but there’s still time to make requests. Just put “Scripting” in the subject line and send them my way.

comments powered by Disqus

Reader Comments:

Mon, Nov 20, 2006 guru1351 Anonymous

works great on w2k3. note that when you save the script you need to piece it back together due to wrap arounds. If you don't know how, you've no business reading mcse sites... :)

Fri, Oct 14, 2005 Peter Modesto

Do you have a script that will automate eseutil in defragment mode through muliple storage groups and information stores on Exchange 2000?

Tue, Jul 6, 2004 Anonymous Anonymous

Thanks, great article - was wondering if there was a way to schedule defrags since you can't do it using Windows Task Scheduler!

Thu, Sep 25, 2003 Puppydog Inglewood CA

What is really going on here? 27,24 this is for w2k servers; no way.

Fri, May 23, 2003 dude overhere

Poor article from a fat lazy author...next time make sure it works and have a section we can download it from to avoid the edits. The column is to learn, so the content should be CORRECT and TESTED.

Thu, May 8, 2003 Anonymous Anonymous

Not a well thought out Column. A great script, however it misleads most people of its actual uses. Better luck next time.

Sat, Mar 15, 2003 Mike from Montreal Anonymous

Does an excellent job on a XP box. To bad it does not run on W2K box. I'll bet it run's on W2K3....

Fri, Mar 14, 2003 Anonymous Anonymous

does not work on w2k

Wed, Mar 5, 2003 MailMan Anonymous

It is a script file folks, get over it. If you don't know how to edit script files or troubleshoot, then you shouldn't be screwing around with scripts.

Mon, Mar 3, 2003 Bryan Starr Denver

To my knowledge, there is no command line defrag in Win2k. Is there a way to accomplish this on Win2k servers?

Thu, Feb 20, 2003 Anonymous Anonymous

This script is a "Frag!" Besides I do not recall during my Marine days using the term frag out. I guess the statement along with this script needs further adjusting!!!

Mon, Feb 17, 2003 Robert Farnes Leeds, UK

Having removed the syntax errors caused by line wrapping I have ascertained that this script is probably for XP since there is no cmd line defrag utility in win2k

Sun, Feb 16, 2003 Jose Campos Downey,CA

Excellent issue to help on PC management tasks, is this script designed for a specific platform? When I run it in a Windows 2000 Pro system it returns the following error message: "C:\DefragDrives.wsf(27, 24) Microsoft VBScript compilation error: Syntax error".

Sun, Feb 16, 2003 Tom Anonymous

Still cannot get this script to work on xp..check the spaces and nothing....

if anyone can send me the script to the email I would appreicated it....

As for the author he should have explained more about it....Thanks...

Tue, Feb 11, 2003 Brad San Antonio

I multi-boot and only found DEFRAG under XP too. Glad to hear someone got it to work. Being that I am not real familiar with scripting, I was hoping to learn a little from this - didn't know I would have to buy a book and learn scripting before learn this script. Wonder what server OS he is referring to in the article.
Also, 10 days worth of comments, and nothing back from the author. Not the kind of followup I have come to expect from MCP Magazine. You would think someone in the staff would have seen the comments and had Mr. Brooke come back with a little more accurate/complete information.

Thu, Feb 6, 2003 dude it will run if you take some time to

This script only works in XP and only if you take the time to go through and verify the lines, some of the lines wrap and they need to be fixed before it will run.

Wed, Feb 5, 2003 Dan Indiana

I get an error (29,8) Object doesn't support WScript.Argurments.Named, on w2k at work and several other errors on my w2k box at home. Was looking forward to using this, but it just doesn't work!

Wed, Feb 5, 2003 Caseman Delaware

I get an error
(27,24) Microsoft VBScript compliation error:systax error

Wint NT 4 SP6a

Wed, Feb 5, 2003 BigWa Anonymous

I was getting the same "defragdrives.wsf(27, 24) Microsoft VBScript compilation error:" This happens if you copy and paste directly from the above article. The problem is because word wrapping adds extra spaces on a few lines. After removing the spaces it worked fine on an XP box.

Tue, Feb 4, 2003 Anonymous Anonymous

Could not get it to run on Windows 2000 SP3 - C:\Scripts\DefragDrives.wsf(27, 24) Microsoft VBScript compilation error: Syntax
error

Tue, Feb 4, 2003 Anonymous Anonymous

No defrag util in W2K

Mon, Feb 3, 2003 Mark Phoenix, AZ

I recieve the "defragdrives.wsf(27, 24) Microsoft VBScript compilation error:" as well. The intro mentions NTFS permissions so I'm assuming the author intended\tested this on NT4 or W2K at least. However, the built in defrag utility with W2K (dfrgntfs.exe) does not support command line use? I'm confused.

Fri, Jan 31, 2003 anonymous Anonymous

syntax errors on w2k

Thu, Jan 30, 2003 Terry Anonymous

Your call to run DEFRAG is not command/utility on any Windows platform by default. Defrag is not part of any any resource kit. Are you by chance neglecting to tell us to download Defrag from Sysinternals.com?

Thu, Jan 30, 2003 SysAdmin CO

This script obviously does not work on most Windows 2000 systems. Did you install a special Developer library, or just leave something out in the script? Don't bother trying this script at home/work because it is nonfunctional.

Thu, Jan 30, 2003 Anonymous Anonymous

Great issue to address since MS does such a poor job allowing easy automation.
Syntax error on w2k. How to run it and prereqs. should be in the script comments.

Thu, Jan 30, 2003 Anonymous Anonymous

Where is the command-line defrag utility in Win2k/XP? Perhaps he is talking about a third party utility?

Wed, Jan 29, 2003 Anonymous Anonymous

I get the same error on Windows XP. Line 7 char24 Syntax Error. VBScript compilation error.

Wed, Jan 29, 2003 Sabatogz Fly Over State

defragdrives.wsf(27, 24) Microsoft VBScript compilation error: Syntax error

Tested on Windows XP Box.

Wed, Jan 29, 2003 John Linebaugh Anonymous

Good column! I have not had time to try it studying for my CCNA. But it does make a lot more sense than having green tanks in the desert. Does it work with XP Professional?

Wed, Jan 29, 2003 Anonymous Anonymous

DefragDrives.wsf(40, 15) (null): The system cannot find the file specified

Win2K SP3

Wed, Jan 29, 2003 Kelly Columbus, OH

I got an error on WinXP. The article mentions running this on servers, so I assumed it was intended for 2000/XP. Is that true?

Tue, Jan 28, 2003 Anonymous Anonymous

Very nice. Although I have lots of people asking me regularly how to write a wsf file and what tags can be used, why. Etc. It seems that the vast majority of the MCSE's I meet (professional employeed in this industry, mostly contractors) do not know how to use or write a wsf. They do understand .vbs. Perhaps more about the how/why etc of wsf files would be a good article for the near future.

Tue, Jan 28, 2003 Anonymous Anonymous

syntax error on W2K!

Mon, Jan 27, 2003 Anonymous Anonymous

Does not say what platform it is for. Also, after figuring it was for the Win9x platform, it doesn't do much good since most enterprises already are migrating to 2000/XP.

Add Your Comment Now:

Your Name:(optional)
Your Email:(optional)
Your Location:(optional)
Comment:
Please type the letters/numbers you see above

Redmond Tech Watch

Sign up for our newsletter.

I agree to this site's Privacy Policy.