PaulSadowski.com 

Windows Scripting Host
 VBScript To Defrag All Hard Drives (XP+ ONLY)
This script runs the command line defrag program included in Windows XP and newer OS'es on all hard drives on your system. The output of the defrag command is redirected to a log file. The log file is defined in the variable LogFile, by default C:\Defrag.log. The Date and time is echoed to the log file before each drive is defragmented.

The script can be run by either Cscript or Wscript. If run by Wscript it will run without displaying any windows.

 

' DefragAll.vbs
' Defrag All Fixed Drives (XP and above ONLY)
' Sat Apr 12 02:54:50 2003
' Copyright © Paul R. Sadowski <scripting@paulsadowski.com>
' All Rights Reserved

Const LogFile = "C:\Defrag.log"

Const DriveTypeRemovable = 1
Const DriveTypeFixed = 2
Const DriveTypeNetwork = 3
Const DriveTypeCDROM = 4
Const DriveTypeRAMDisk = 5

Set FSO = CreateObject("Scripting.FileSystemObject")
Set Drives = FSO.Drives

For each Drive in Drives
 if Drive.DriveType = 2 then
  RunCmd Drive
 end if
Next

Sub RunCmd(DriveString)
Set WshShell = WScript.CreateObject("WScript.Shell")
RunString = "%comspec% /c echo " & WeekDayName(WeekDay(Now), True) & " " & Now & " " & DriveString
Return = WshShell.Run(RunString & " >> " & LogFile & " 2>&1", 0, TRUE)
RunString = "%comspec% /c %WINDIR%\System32\Defrag.exe " & DriveString & " -f"
Return = WshShell.Run(RunString & " >> " & LogFile & " 2>&1", 0, TRUE)
Set WshShell = Nothing
End Sub

 

© 2003 by Paul R. Sadowski   
All Rights Reserved. Used By Permission.  
Comments to: Scripting