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:
- Identify all local hard drives,
- Work out how defragmented the drive is,
- Defrag the drive,
- Show how much less it is fragmented afterwards,
- Log it all to a file
- 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…
- 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,
- then use the Win32_DefragAnalysis class to work out how fragmented the drive is,
- then use Defrag Method associated with the Win32_Volume class,
- repeat step 2,
- Log it all using the start-transcript and stop-transcript cmdlets,
- 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