Automated DeFrag of Hard drives.

Posted on 2005-04-15
Medium Priority
Last Modified: 2008-03-04
Hi there,we have 3 HP ML350's running various amounts of SCSI disks all in raid  I'm looking for a way to defrag our servers automaitcally overnight, I'm sure there's a way to do it but all my efforts so far have achieved nought. Should I be using a comercial product?

I've also got a machine acting as a storage area for our daily backups, it's a WinXp Pro Sp2 box fitted with 4 Maxtor 300Gb SATA drives in an Adaptec RAID caddy (2410) setup as raid 5. So basically I have a about 870Gb's of space and it's gonna take and awful long time to defrag 3% took 5 hours yesterday. We're using Veritas 9 on one of our 2003 boxes to do the backup and it sends it down the line in 1Gb chunks (60 of them a night at the moment) I'd like to automate a defrag for this also.

 Any ideas would be greatly appreciated.

I'm after info from people with such a setup running really, rather than a bunch of google links.  :P
Question by:Wafu
  • 4
  • 3
  • 2
  • +2

Assisted Solution

joedoe58 earned 1000 total points
ID: 13789274
You have several options of 3'd party like O&O Defrag or Diskeeper that will do the job nicely. You could also use scheduler to set up an automatic defrag with the included defrager of windows but i doubt if you have a window big enough to do so at night. The programs i mentioned do so in the background. You can download trials from their home pages
LVL 18

Accepted Solution

Steve McCarthy, MCSE, MCSA, MCP x8, Network+, i-Net+, A+, CIWA, CCNA, FDLE FCIC, HIPAA Security Officer earned 1000 total points
ID: 13790234
Diskeeper Server 9 is the way to go.  Use the Set it and Forget it functionality and you will be defragmenting on whatever schedule you specify.  Windows defragger is OK and you can use scheduler, however it doesn't always work and in the Windows world, their defragger has always been so so to OK for use.  Diskeeper is made for Defragmentation.  That's all it does and it is at the top of the defragger foodchain.


Expert Comment

ID: 13790533
You can make use of the Scheduler and a script to defrag for you when ever you like. Just schedule a task to run this script whenever you want the defrag to begin. Drop this code into a .VBS file.

Defragments volume D on a computer. If you modify this script to defragment a different volume (such as X), note that your WQL query must specify the drive letter followed by a colon and then followed by two slashes. Thus volume X would be listed as X:\\.
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colVolumes = objWMIService.ExecQuery _
    ("Select * from Win32_Volume Where Name = 'D:\\'")

For Each objVolume in colVolumes
     errResult = objVolume.Defrag()

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.


Expert Comment

ID: 13793304
ScriptMasta's .vbs is very good solution for you Wafu. Free and works.

See also Win32_DefragAnalysis -class for information how fragmented your drives are and defrag if needed.

Try "Win32_Volume wmi" at Google.

Expert Comment

ID: 13793461
This is out of scope of the original question but I just post this anyway...

A nice solution would be to create a vbs script that determines if defrag sould be run and logs status and results to Windows EventLog.

Create a vbs-script:

* Use Win32_DefragAnalysis -class to determine if defrag sould be run, log status of defragmentation to Application Log.
* Run defrag (if needed) with WMI Win32_Volume -class. Log results to App.Log
* Again, log status of fragmentation to Log.
* Create a Scheduled Task to run the script.

"eventcreate /?" in Command Prompt gives you help how to create own events to EventLog.

If I remeber right, you can log events with vbs-scripts but I dont remember how. Perhaps the "eventcreate" is better because you can also set the EventSource, with vbs its allways "wscript" or similiar.

Expert Comment

ID: 13801994
ok, I just for "fun" created a script to defrag W2K3 volumes:

' ------------------------------------------------------------
' Defragger.vbs - Script to analyze disk fragmentation
' and to run defrag.
' Parameters:
'      1) Computer to be examined
'      2) Drive to defrag, empty string "" means all drives
'      3) ForceDefrag - True/False to Force Defrag even if it is not needed
' Usage examples:
'      cscript //nologo Defragger.vbs Server01 C False -> Analyse and defragment C -drive of Server01
'      cscript //nologo Defragger.vbs Server03 "" False -> Analyse and defragment All drives of Server03
'      cscript //nologo Defragger.vbs MyServer "" True -> Analyse and Force defragmentation All drives of MyServer
' Defragger.vbs - 17.04.2005 - Ver 0.1
' ------------------------------------------------------------

Dim arrArgs
Dim strComputer
Dim strDrive
Dim strForce

arrDefragResults = Array("Success", "Access denied", "Not supported", _
      "Volume dirty bit is set", "Not enough free space", "Corrupt Master File Table detected", _
      "Call cancelled", "Call cancellation request too late", "Defrag engine is already running", _
      "Unable to connect to defrag engine", "Defrag engine error", "Unknown error")

' ----- Main
      RunAnalysis strComputer, strDrive, strForce
Function CheckArgs()
      Set arrArgs = Wscript.Arguments
      If arrArgs.Count <> 3 Then
      End If
      strComputer = arrArgs(0)
      strDrive = arrArgs(1)
      strForce = arrArgs(2)
End Function

Function Usage()
      Wscript.Echo "Defragger.vbs - Script to defrag W2003 disks" & vbNewline
      Wscript.Echo "USAGE: cscript //nologo <computername> <driveletter> <forcedefrag>" & vbNewline
      Wscript.Echo vbTab & "<computername> - computer where to run defrag"
      Wscript.Echo vbTab & "<driveletter> - specify dirve to analyze and defrag," & vbNewline & _
            vbTab & vbTab & "enter empty string """" to analyse and defrag all drives."
      Wscript.Echo vbTab & "<forcedefrag> - True/False fo force defrag (even if it is not needed)" & vbNewline
      Wscript.Echo "Example: cscript //nologo MyServer F False"
      Wscript.Echo "Example: cscript //nologo OtherServer """" True" & vbNewline
      Wscript.Echo "Use Event Viewer to examine results in Application log"
End Function

Function RunAnalysis(strComputer, strDrive, strForce)      
      Set objWshShell = Wscript.CreateObject("WScript.Shell")
      Set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
      If strDrive <> "" Then
            Set colVols = objWMI.ExecQuery("Select * from Win32_Volume " & _
                  "where DriveType = 3 and Name = '" & strDrive & ":\\'")
            Set colVols = objWMI.ExecQuery("Select * from Win32_Volume where DriveType = 3")
      End If
      for each objVol in colVols
            'strMsg = "Script Parameters: """ & strComputer & """, """ & strDrive & _
            '      """, """ & Cbool(strForce) & """" & vbNewline & vbNewline
            strMsg = "Analyzing Computer: " & strComputer & vbNewline & vbNewline
            strMsg = strMsg & "Analyzing volume " & objVol.DriveLetter & vbNewline & vbNewline
            intRC = objVol.DefragAnalysis(boolDefrag, objRpt)
            if intRC = 0 then
                  strMsg = strMsg & "Volume " & objVol.DriveLetter & " fragmentation report:" & vbNewline & vbNewline
                  strMsg = strMsg & "Volume size: " & objRpt.VolumeSize & vbNewline
                  strMsg = strMsg & "Cluster size: " & objRpt.ClusterSize & vbNewline
                  strMsg = strMsg & "Used space: " & objRpt.UsedSpace & vbNewline
                  strMsg = strMsg & "Free space: " & objRpt.FreeSpace & vbNewline
                  strMsg = strMsg & "Percent free space: " & objRpt.FreeSpacePercent & vbNewline
                  strMsg = strMsg & "Total fragmentation: " & objRpt.TotalPercentFragmentation & vbNewline
                  strMsg = strMsg & "File fragmentation: " & objRpt.FilePercentFragmentation & vbNewline
                  strMsg = strMsg & "Free space fragmentation: " & objRpt.FreeSpacePercentFragmentation & vbNewline
                  strMsg = strMsg & "Total files: " & objRpt.TotalFiles & vbNewline
                  strMsg = strMsg & "Average file size: " & objRpt.AverageFileSize & vbNewline
                  strMsg = strMsg & "Total fragmented files: " & objRpt.TotalFragmentedFiles & vbNewline
                  strMsg = strMsg & "Total excess fragments: " & objRpt.TotalExcessFragments & vbNewline
                  strMsg = strMsg & "Avg fragments per file: " & objRpt.AverageFragmentsPerFile & vbNewline
                  strMsg = strMsg & "Page file size: " & objRpt.PageFileSize & vbNewline
                  strMsg = strMsg & "Total page file fragments: " & objRpt.TotalPageFileFragments & vbNewline
                  strMsg = strMsg & "Total folders: " & objRpt.TotalFolders & vbNewline
                  strMsg = strMsg & "Fragmented folders: " & objRpt.FragmentedFolders & vbNewline
                  strMsg = strMsg & "Excess folder fragments: " & objRpt.ExcessFolderFragments & vbNewline
                  strMsg = strMsg & "Total MFT size: " & objRpt.TotalMFTSize & vbNewline
                  strMsg = strMsg & "MFT record count: " & objRpt.MFTRecordCount & vbNewline
                  strMsg = strMsg & "MFT percent in use: " & objRpt.MFTPercentInUse & vbNewline
                  strMsg = strMsg & "Total MFT fragments: " & objRpt.TotalMFTFragments & vbNewline
                  If boolDefrag Then
                        strMsg = strMsg & vbNewline & "You should defragment this volume."
                        strMsg = strMsg & vbNewline & "You do not need to defragment this volume."
                  end if
                  strMsg = strMsg & "Error during defragmentation analysis: " & arrDefragResults(intRC)
            end if
            objWshShell.Run "C:\WINDOWS\System32\eventcreate.exe " & _
                  "/T Information /L Application /id 1 /SO ""Defragger Script"" " & _
                  " /D """ & strMsg & """"

            If boolDefrag Or Cbool(strForce) Then
                  ' ----- Running Defrag on given volume
                  strTmp = "Defragmenting of " & strComputer & " volume " & objVol.DriveLetter & " started at " & Now()
                  objWshShell.Run "C:\WINDOWS\System32\eventcreate.exe " & _
                        "/T Information /L Application /id 1 /SO ""Defragger Script"" " & _
                        " /D """ & strTmp & """"
                  ' ----- Change False -> True to force defrag
                  nResult = objVol.Defrag(Cbool(strForce), objDefRpt)
                  ' ----- Create report of defragmentation
                  strDRptTmp = "Volume " & objVol.DriveLetter & " fragmentation report:" & vbNewline & vbNewline
                  strDRptTmp = strDRptTmp & "Volume size: " & objDefRpt.VolumeSize & vbNewline
                  strDRptTmp = strDRptTmp & "Cluster size: " & objDefRpt.ClusterSize & vbNewline
                  strDRptTmp = strDRptTmp & "Used space: " & objDefRpt.UsedSpace & vbNewline
                  strDRptTmp = strDRptTmp & "Free space: " & objDefRpt.FreeSpace & vbNewline
                  strDRptTmp = strDRptTmp & "Percent free space: " & objDefRpt.FreeSpacePercent & vbNewline
                  strDRptTmp = strDRptTmp & "Total fragmentation: " & objDefRpt.TotalPercentFragmentation & vbNewline
                  strDRptTmp = strDRptTmp & "File fragmentation: " & objDefRpt.FilePercentFragmentation & vbNewline
                  strDRptTmp = strDRptTmp & "Free space fragmentation: " & objDefRpt.FreeSpacePercentFragmentation & vbNewline
                  strDRptTmp = strDRptTmp & "Total files: " & objDefRpt.TotalFiles & vbNewline
                  strDRptTmp = strDRptTmp & "Average file size: " & objDefRpt.AverageFileSize & vbNewline
                  strDRptTmp = strDRptTmp & "Total fragmented files: " & objDefRpt.TotalFragmentedFiles & vbNewline
                  strDRptTmp = strDRptTmp & "Total excess fragments: " & objDefRpt.TotalExcessFragments & vbNewline
                  strDRptTmp = strDRptTmp & "Avg fragments per file: " & objDefRpt.AverageFragmentsPerFile & vbNewline
                  strDRptTmp = strDRptTmp & "Page file size: " & objDefRpt.PageFileSize & vbNewline
                  strDRptTmp = strDRptTmp & "Total page file fragments: " & objDefRpt.TotalPageFileFragments & vbNewline
                  strDRptTmp = strDRptTmp & "Total folders: " & objDefRpt.TotalFolders & vbNewline
                  strDRptTmp = strDRptTmp & "Fragmented folders: " & objDefRpt.FragmentedFolders & vbNewline
                  strDRptTmp = strDRptTmp & "Excess folder fragments: " & objDefRpt.ExcessFolderFragments & vbNewline
                  strDRptTmp = strDRptTmp & "Total MFT size: " & objDefRpt.TotalMFTSize & vbNewline
                  strDRptTmp = strDRptTmp & "MFT record count: " & objDefRpt.MFTRecordCount & vbNewline
                  strDRptTmp = strDRptTmp & "MFT percent in use: " & objDefRpt.MFTPercentInUse & vbNewline
                  strDRptTmp = strDRptTmp & "Total MFT fragments: " & objDefRpt.TotalMFTFragments
                  strTmp = "Defragmenting of " & strComputer & " volume " & objVol.DriveLetter & _
                        " ended at " & Now() & vbNewline & vbNewline & _
                        "Result of defrag was " & arrDefragResults(nResult) & vbNewline & vbNewline
                  strTmp = strTmp & strDRptTmp       
                  objWshShell.Run "C:\WINDOWS\System32\eventcreate.exe " & _
                        "/T Information /L Application /id 1 /SO ""Defragger Script"" " & _
                        " /D """ & strTmp & """"
            End If
End Function

Expert Comment

ID: 13802401
It is nice to see all the scripts that will do a nice job of defragging. The only problem is that during defragg the server will be bogged down to a crawl and the question is if that is acceptable since a defrag will probably run into working hours. A comercial product like diskeeper or O&O defrag does not have that problem since they do defrag with a minimum of CPU overheed and they also do a much better work of defraging.

Expert Comment

ID: 13802524
well joedoe58, remember that the script itself wont do the defragging but only start defragging engine (dfrgntfs.exe) and defragging is not dependent on processor time but disk speed. We're not calculating (CPU dependent) when defragging, only organizing and moving files (DISK depenedent).

True is that commercial products like O&O do better work, MS Defrag simply wont defrag everything.

thus answer to original question would be:

A) By some commecial product that has scheduling options and does better work but costs money
B) Use script provided and schedule yourself, defrag efficiency is not so good but money is saved


Author Comment

ID: 13803971
I'm gonna take an hour out later and work through the scripts then I'll accept an answer or share the points. It always a little hard to decide award points when it's advice you're seeking rather than an out and out fault. Thanks for everything sofar guys..

Expert Comment

ID: 13804569
It is true that it does not do calculating but someone still have to decide to do a write and delete request to the disk, and that will hurt your performance of your server. And the implemention of MS Defrag, who is a "dumb" version of diskeeper, do requrie much more muscle from your system than other products. Still if performance is not an issue but money is, then by all means go with MS Defrag.

Author Comment

ID: 14210768
Well we choose Diskeeper9 in the end. Very good product and can handle volumes running shadow copy too. But it ain't cheap, £400 per copy for the Enterprise Edition and that was INCLUDING educational discount. Also be sure to choose the right version, the only one to handle TeraBytes is the enterprise version.

Hopefully some of the excellent scripts above will help people on a budget and I appreciate the time of  ajsaasta for putting those together.

Anyway we shaved over 90 minutes off the backup and verify operation daily so if you have the cash, eval it it, if not go for a script. Thanks Joedoe58.

Featured Post

Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

On July 14th 2015, Windows Server 2003 will become End of Support, leaving hundreds of thousands of servers around the world that still run this 12 year old operating system vulnerable and potentially out of compliance in many organisations around t…
Learn about cloud computing and its benefits for small business owners.
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question