Automatic Defrag of Hard Drives With No User Input or Intervention
Posted on 25 April 2007 by admin
Instead of manually scanning your hard drive to see if you need to defrag it, or dropping a bundle of money on a Defragging Program such as DiskKeeper, you can use the builtin Windows features to keep your disks optimized and never have to intervene manually or launch anything.
The command-line Defrag program (defrag.exe) supports -a switch, which can analyze the specified volume, and notifies you if defragmentation for that volume is necessary or not. Here is a sample output, when used the -a switch is used:

Use the VBScript below, which invokes the defrag analysis for each drive in a Command Prompt window, and reads the Analysis Report that is produced to know if the drive needs to be defragmented or not. The step is repeated for every fixed disk present in the system.
‘———————————————————
‘Authored by : WWW.GOITEXPERT.COM
‘VBScript to defrag all the drives, only if fragmented.
‘The script reads the Defrag Analysis Report to generated by
‘defrag -a to know if the drive(s) need to be defragmented.
‘———————————————————
Set objShell = CreateObject("Wscript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
strSearch = "You do not need to defragment this volume."
Const MIN_INACTIVE = 7
Set colDrives = objFSO.Drives
For Each objDrive in colDrives
If objDrive.DriveType = 2 Then
Set objWshScriptExec = objShell.Exec("defrag.exe " _
& objDrive.DriveLetter & ": -a")
strOutput=objWshScriptExec.StdOut.ReadAll
If InStr(1, strOutput, strSearch) = 0 Then
objShell.Run "defrag.exe " _
& objDrive.DriveLetter & ":", MIN_INACTIVE ,True
End If
End If
Next
Set objShell = Nothing
Set objFSO = Nothing
Copy the above contents and Paste it in Notepad. Save the file with a .VBS extension. You can then double-click the file to run it, or, you can even schedule this script using Windows Task Scheduler or put it in the Startup Folder in Windows. Alternatively you can download the ready to go VBS script here.
If you want to only defragment the c drive use the code below:
‘———————————————————
‘Authored by : WWW.GOITEXPERT.COM
‘VBScript to defrag the c drive, only if fragmented.
‘The script reads the Defrag Analysis Report generated by
‘defrag -a to know if the c drive needs to be defragmented.
‘———————————————————
Set objShell = CreateObject("Wscript.Shell")
Set objWshScriptExec = objShell.Exec("defrag.exe c: -a")
strOutput=objWshScriptExec.StdOut.ReadAll
strSearch = "You do not need to defragment this volume."
If InStr(1, strOutput, strSearch) = 0 Then
objShell.Run ("defrag.exe c: -w")
End If
Alternatively, you can download the VBS file here.
Tags | Disaster Recovery, General, Networking, Windows Vista, Windows XP
