Automated and scheduled HD defragmenting

Some time ago I wrote a script to automate disc defragmenting so that I could schedule it to late nights when no one is using the computer anyway. It turned out to be quite simple using VB scripting and Windows scheduler. Below you can see the commented script I use. You might need to make a couple of modifications if you have a localized copy of Windows (keyboard short-cuts and application names may be different).

Copy and paste the script to an empty Notepad and save as HDdefrag.vbs or something similar, in a suitable folder. Then go to the Scheduled Tasks (Windows XP) and  select Add Scheduled Task.  Then just follow the instructions in the Wizard to make the script run every 2 weeks or so. You can even make your computer wake up if you have it in hibernation mode.

set WshShell = CreateObject(“WScript.Shell”)

‘Launch Defrag from the command line and wait for 2000 milliseconds
WshShell.Run “dfrg.msc”
WScript.Sleep 2000

‘Wait until the application has loaded – Check every second
While WshShell.AppActivate(“Disk Defragmenter”) = FALSE
wscript.sleep 1000
Wend

’1 Bring the application to the foreground
WshShell.AppActivate “Disk Defragmenter”
WScript.Sleep 500

’1 Send keys to move to top of drive/partition table.
WshShell.SendKeys “{TAB}{HOME}”
WScript.Sleep 501

’1 Send an ALT-A key to bring down the defrag menu
WshShell.SendKeys “%A
WScript.Sleep 502

’1 Send a D to start the defrag
WshShell.SendKeys “D”

’1 Wait until the defrag is completed – Check for window every 5 seconds
While WshShell.AppActivate(“Defragmentation Complete”) = FALSE
wscript.sleep 5001
Wend

’1 Bring the Defragmentation Complete window to the foreground
WshShell.AppActivate “Defragmentation Complete”
WScript.Sleep 503

’1 Send a tab key to move the focus from View Report button to the Close Button
WshShell.Sendkeys “{TAB}”
Wscript.Sleep 504

’1 Send key to Close the Defragmentation Complete window
WshShell.Sendkeys “{ENTER}”
Wscript.Sleep 505

Popularity: 6% [?]

Comments are closed.