Tuesday, 15 December 2009

Defragmenting drives with PowerShell: updated

A while back I posted about how it was possible to defrag a disk with PowerShell but ended the post saying that I would probably never need to use it.  Turns out that I did need to after all…

It had been quite some time since I’d defragmented either the drive in my main PC at home or any of the external hard drives connected to it.  What I wanted to to be able to do with a PowerShell script was:

  1. Identify all local hard drives,
  2. Work out how defragmented the drive is,
  3. Defrag the drive,
  4. Show how much less it is fragmented afterwards,
  5. Log it all to a file
  6. Then shutdown the PC (given that if I’m sitting in front of this PC I tend to be playing Team Fortress 2 I wanted it to run when I’d finished then shut the box down.  I know that defrag will fall back into the background if it detects that the user is doing anything but given my n00bTF2 skills I can’t afford to hamper my performance!).

Using the code I posted previously as a starting point, turned out that it was pretty easy to achieve everything I wanted the script to do…

image

  1. Identify all local hard drives using Win32_Volume class, checking that DriveType equals 3 (a local drive) and that there is a drive letter assigned,
  2. then use the Win32_DefragAnalysis class to work out how fragmented the drive is,
  3. then use Defrag Method associated with the Win32_Volume class,
  4. repeat step 2,
  5. Log it all using the start-transcript and stop-transcript cmdlets,
  6. and finally shutdown the PC using the stop-computer cmdlet.

This will only run on Vista and later and needs to be run elevated, but it means that I can defrag my drives and shut my PC down without having to leave it on and rely on scheduling and it’s one less excuse I have for being beaten on TF2 again….

No comments:

Post a Comment