Scheduled automatic hard drive defragmentation for Windows Server 2003

March 16th, 2007

The problem

Suppose you are the administrator of one or more servers running Windows Server 2003. You probably have a schedule of maintenance tasks you perform on a periodic basis, such as checking system logs, installing software updates, maintaining security policies, cleaning up users’ files and defragmenting the hard drives.

For the last activity, you may have opted for a third party solution such as O&O Software’s Defrag for servers. I love and trust this solution — it’s a powerful and flexible tool specialized on defragmenting drives, making this recurring activity a breeze to manage.

But what if you’re in a corporate environment that, for several reasons, will stick to the Windows built-in defragmenter? Would you spend several hours a week attending to manually defragmenting drives and be happy with it? That’s silly.

Fortunately, unlike the Windows XP counterpart, the defragmenter application in Windows Server 2003 can be started from a batch script, so you can automatize the defragmentation activity. But things get a little more complicated if you have several partitions you want to defragment or if you want to perform more advanced tasks.

The needs

Here’s what I wanted:

  • Defragment all drives and partitions in the system sequentially (one after another).
  • Prevent multiple instances of the defragmenter from running in parallel.
  • Defragment only if there is sufficient free disk space for the defrag to work optimally (minimum 15% of disk space free).
  • Defragment only if the defragmenter recommends it, so it doesn’t run on drives with a 2% fragmentation.
  • Log the activity somewhere — I chose the system log for it, since I’m already checking it at least once a week, but this can be done easily in a text file.
  • Prepare for possible errors and log them.

I studied several scripts for automatic defragmentation on the web and built my own, to match my needs. Credit and thanks goes to everyone else who has attempted this in the past.

The script

' Unattended defragmentation script for Windows Server 2003
' Checks all hard drives and defragments them as necessary
' Create a BAT file with the following command:
'     CSCRIPT AutoDefrag.vbs //B
' Call the BAT file from Scheduled Task, run as Administrator or another user with rights for defragmenting disk
Const EVENT_SUCCESS = 0
Const EVENT_ERROR = 1
Const EVENT_WARNING = 2
Const EVENT_INFORMATION = 4
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objShell = CreateObject("Wscript.Shell")
' Check if another instance of Windows Defrag is already running
Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = ' Dfrgntfs.exe'")
If colProcesses.Count = 0 Then
	' No other instance found
	' Write information message in the system log
	objShell.LogEvent EVENT_INFORMATION, "Starting unattended disk defragmentation."
	' Find all hard drives
	Set colVolumes = objWMIService.ExecQuery("Select * from Win32_Volume where DriveType = 3")
	For Each objVolume in colVolumes
		' Analyze drive, check if it is recommended to defragment it
		errResult = objVolume.DefragAnalysis(blnRecommended, objReport)
		' Check if the operation completed without errors
		If errResult = 0 Then
			' Fragmentation check completed without errors
			' Check if there is sufficient free space on disk for defragmentation (minimum 15%)
			If (objReport.FreeSpacePercent < 15 ) Then
				' Drive doesn't have enough free space for an efficient defragmentation
				' Write error message in the system log
				objShell.LogEvent EVENT_WARNING, "Drive " & objVolume.Name & " is almost full and cannot be defragmented! Drive is " & objReport.FreeSpacePercent & "% free."
			Else
				' There is enough free space
				' Is it is recommended to defragment current drive?
				If (blnRecommended) Then
					' Yes, current drive should be defragmented
					' Write information message in the system log
					objShell.LogEvent EVENT_INFORMATION, "Drive " & objVolume.Name & " should be defragmented: " & objReport.TotalPercentFragmentation & "% total fragmentation, " & objReport.FilePercentFragmentation & "% file fragmentation. Drive is " & objReport.FreeSpacePercent & "% free."
					' Begin defragmentation
					errResult = objVolume.Defrag()
					' Check if defragmentation completed without errors
					If errResult = 0 Then
						' No errors, defragmentation is complete
						' Write information message in the system log
						objShell.LogEvent EVENT_SUCCESS, "Drive " & objVolume.Name & " successfully defragmented."
					Else
						' Error encountered
						' Write error message in the system log
						objShell.LogEvent EVENT_SUCCESS, "Drive " & objVolume.Name & " could not be defragmented. Error code: " & errResult & "."
						Err.Clear
					End If
				Else
					' No, current drive doesn't need to be defragmented
					' Write information message in the system log
					objShell.LogEvent EVENT_SUCCESS, "Drive " & objVolume.Name & " does not need to be defragmented: " & objReport.TotalPercentFragmentation & "% total fragmentation, " & objReport.FilePercentFragmentation & "% file fragmentation. Drive is " & objReport.FreeSpacePercent & "% free."
				End If
			End If
		Else
			' Fragmentation check generated an error
			' Write error message in the system log
			objShell.LogEvent EVENT_WARNING, "Drive " & objVolume.Name & " could not be analyzed. Error code: " & errResult & "."
		End If
	Next
	' Finished checking and defragmenting all hard drives in the system
	' Write information message in the system log
	objShell.LogEvent EVENT_INFORMATION, "Unattended disk defragmentation is complete."
Else
	' Another instance of Windows Defrag already running
	' Write error message in the system log
	objShell.LogEvent EVENT_ERROR, "Unattended disk defragmentation is unable to start: another instance of NTFS Defrag is already running."
End If

How to use this?

  1. Copy and paste this text in Notepad, save the text file as autodefrag.vbs in a folder on your Windows Server 2003 machine.
  2. In another Notepad window, enter the command: cscript autodefrag.vbs //B and save it as autodefrag.bat in the same folder with autodefrag.vbs .
  3. Create a new scheduled task that runs autodefrag.bat whenever you want. Make sure you run this under an account with administrative priviledges.

Tips

  • Schedule automatic defragmentation at a time when it doesn't conflict with other disk-intensive activities, such as file transfers, database backups, file archival, tape backups, other maintenance.
  • Check logs to make sure the defragmentation ended without errors.
  • If a partition is almost full, free up some space and defragment it manually.
  • Check if partitions that were skipped by the automatic defragmenter really do not need to be defragmented.
  • For optimum performance, prepare your drives before automatic defragmentation commences -- delete temporary files, archive logs and other files.
  • Augment this script to write details of its actions in a separate log file you can back up or send by e-mail, as needed. On request, I could prepare a version which also uses text files for logs.

If you find this script useful, I'd really like to hear your experiences with it.

To Bob Average, amateur holiday photographer

November 14th, 2006

Dear Bob,

Before you leave on your trip, please allow me to give you a few tips which might help you come back with the greatest holiday photos you have ever taken.

1. The camera manufacturer labeled it “point and shoot” implying the ease of photo taking from a technological point of view — no more fiddling with manual controls. This, however, doesn’t mean that you will actually get some decent photos without prior thinking for a fraction of a second. So don’t click your finger sore, as this approach will only generate some thick photo albums filled with garbage and a group of irritated fellow tourists. Yes, garbage — just because it’s yours doesn’t make it any less than that.

2. Your average camera’s flash can only illuminate subjects up to about 10, maybe 12 feet (3 to 4 meters) away. For anything farther away or for taking photos through the window of your hotel or bus, please learn how to turn off your flash. Otherwise, not only will your photos be ruined, but it’s plain stupid to use the flash when taking a photo at a distant mountain, at a yacht far away on the open sea, the city lights a few miles below the airplane, and so on. Your flash can’t reach the subject, and can’t illuminate it sufficiently in the darkness.

3. Amazingly, when you hold the camera to take a photo, your feet are still able to move around. Instead of standing frozen in place and leaning backwards in awkward body postures, or asking your family members to move “a bit to the left, no, back to the right a tad, too much, come back, there, smile, no, go back, why can’t you people stand still for a second” for two minutes for each photo, take a few steps back or to a side to reach the angle you want.

This particularily applies to stupid photos you’ve seen of people apparently pushing from a side on the Leaning Tower of Pisa, or holding the Eiffel Tower from its tip, or other idiotic postures you thought were “cool” and plan to reproduce with your own family members. Don’t annoy them (and hundreds of other tourists around) for half an hour until you get that “perfect” shot, telling your subject to move a matter of inches. Shift your body position so the person and the monument align the way you want them to. Don’t forget to label these photos as “Idiot pretending to hold the largest European stadium in his hand” and show them to everyone you know, pay close attention to their actual level of interest.

4. When you plan to visit a large monument, such as the Leaning Tower of Pisa, the Eiffel Tower or the World Trade Center, remember well in advance that you want a photo of that monument. Most likely your average camera doesn’t have a wide angle lens and the monument won’t fit in the frame when you’re two feet from the entrance. No, taking 30 steps back peeping forward through the viewfinder or watching the camera screen in front of you, and without looking whom you’re bumping into, will not be far enough for the monument to fit. If you forgot to take the photo at the right time, just let it go; take the photo on your exit, or buy postcards photographed by professionals.

5. When taking photos of a person a few feet away, don’t aim the camera so his or her head is dead center in the picture. You are allowed to move your eye and look at the whole frame before taking the shot. Learn to frame the person correctly and don’t butcher their feet off while filling the upper half of the photo with the naked sky. The 5 typical framings for a person are: the face, the chest and head, from waist up, knees up and full body; all usually imply that the person’s figure takes up most of the frame, not just the bottom half. In full body photos or groups, always watch the feet and make sure they fit. Don’t cut off the foundation (and, if possible, tip) of a building either.

6. If you bother to take photos, photograph something that is interesting to see even some time later. The photo should be able to speak for itself, to tell a story, to have a main character and make a point. We’re all tired of looking at a photo documentary of everything you have seen on your trip, with the message “This is what I saw.” I’m sure you feel that you feel the need to explain everything in these photos every time you show them to someone. “These are the slippers from the hotel. That’s the standard TV remote control. This is the dull view from the window. Over here we have a blue sky, which is completely different than the blue sky you can see from your own home. Yeah, they also have nice sunsets in Austria; who would have thought? I brought back evidence, though. This photo I took from the bus and it’s a donkey on the side of the road, but the bus moved so I only caught the back legs and you can barely make them out because of the camera shaking-induced blur. Trust me, it was a donkey, even if you can’t see it.” Just stop. Please.

7. Even worse than watching everything on your trip through the camera’s viewfinder and photographing every stupid, insignifiant detail, is taking awkward photos of your head and maybe some piece of body in the forerground, with a tourist attraction poorly framed in the background. Such photos scream “This is proof I went there.” That’s really, really pathetic. Do you need to brand your photos in that way, so they can be returned to their rightful owner in case they get lost, or maybe preventing your co-workers from stealing them and claiming it was their trip? I’m sure your friends will believe that you took the photo even if you’re not in it. Are you part of the overall picture, the surroundings, or a piece of the story you want to transmit through that photo? Do you fear your memory will eventually fail so bad that you need photos to remind you where in the world have you been? Stop embarassing yourself.

8. Keep in mind that you went on holiday to get some peace and relaxation, not to work at getting photos. Pocket your camera and watch the world around you through your own eyes. Breathe the air, experience the different culture, enjoy yourself. Take photos only if you strongly believe they are worth it. Otherwise, buy the nicest of the gazillion postcards available nearly everywhere. Professional photographers have better equipment than you, better knowledge than you, better experience than you; let them do the work for you. Trust me, nobody back home will get pissed if you don’t show them a bad photo of the Great Pyramid, which they have already seen on TV plenty of times, nor will they care about a dark sarcophagus you don’t know anything about. Do yourself a favor and use your camera with moderation; the fact that you own a camera doesn’t mean you have to use it all the time.

Thanks and have a great time!

Got books

October 15th, 2006

In recent years, all the books I’ve read were either for school or technical-related, while the little literature I’ve read was in electronic format.

I love e-books: not collecting dust and not taking up space on shelves, usually cheaper than their printed versions, and environmentally friendly. I can deal with reading on a computer display, while I appreciate the search ability of an electronic document.

But for my birthday, I bought myself a few books from Amazon.com. Real books. Words on paper. They’re books I have been looking forward to read for quite some time. Now that they’re here, I can almost taste the thrill of anticipation. Here’s the list:

“A Whole New Mind” caught my attention in February 2005, just a couple of months before it was published. Daniel Pink’s article “Revenge of the right brain” in Wired Magazine briefly brought up the main points of the book. It was equally a very interesting reading, and proof that Daniel Pink has an excellent writing style. The subject came in right on time to fuel my interest in self-development and potential trends in work environment. “Free Agent Nation” is now about to continue building on those thoughts.

Thomas Friedman has made excellent points on globalisation in his earlier work. I’m very curious on what synapses will be fired by this new book of his.

Hands down, these will be the most interesting things I have read in recent years. Even before I opened the covers, I highly recommend them to you. At least read Daniel Pink’s article and see if anything clicks for you.

Tinkering with capacitors

October 15th, 2006

Yesterday I finally had the time to shop for replacement capacitors for the Dell desktop I bought for a file server, whose 5 capacitors were swollen.

Somehow electronic parts shops are all grouped together on the same street in this city, stretching for a couple hundred meters on both sides. I needed 5 capacitors of 2200 microfarads at 6.3 volts. Armed with patience and enjoying the warmth of the late autumn sun, I went through all the shops in a few hours. It’s pretty difficult to find capacitors for such a low voltage; some shops only carried from 10 or 16 volts up, others only from 50 up.

I started with largest electronic parts distributors. One didn’t have what I needed, another had the 10 volt kind – so I bought 10 of them for about $4. Cheap for a reason: their brand is “NA.” Not Applicable? Yikes. I’d better find alternate options.

Across the street, a smaller shop carried the kind I wanted – 6.3 volts. A bit more expensive, I bought only 5 of them for $4, but I wasn’t confident they were any better. They are dark blue with golden markings, made by “Kingcon.” Never heard of this one either, but they look a lot like those I’ve seen swelling up, and the brand sounds a lot like the 5 faulty capacitors in the Dell, “Nickicon.”

On a side note, what were Foxconn thinking when they picked “Nickicon” as a component supplier for manufacturing motherboards for Dell?!

Anyways, I went through the other stores, many being specialized in audio parts – speakers, amplifiers, specialty audio cables and connectors, and ultra-high performance electronic components for hi-fi audio devices. In such a small shop I found the kind of capacitors I needed, but this time a well-known, trusted brand: Jamicon. Clearly, these capacitors were nearly $1 a piece, but it’s money well spent.

Later in the day, I replaced the faulty capacitors on the motherboard with these Jamicon gems, powered up the desktop and… it started beeping at me. For a few seconds, I froze. Then I looked at the 4 diagnostic LEDs on the back of the Dell – two orange, two green. I looked up the pattern in the troubleshooting section of the manual and sighed with relief: “Bad memory.” I knew one of the memory modules has been acting weird, and this time I got proof: self-check identified two faulty locations. After taking the module out, everything worked perfectly.

Now I’ve got a new story to tell, a working file server, 15 capacitors I don’t need, and a deffective SDRAM memory module as a fancy keychain.

Bad capacitors, take three

October 1st, 2006

It happened again.

The first time it was an accidental discovery. I was happy to think that I have fixed the problem.

The second time it was a surprising discovery, but I was convinced that the second blow will finally kill the monster.

But it didn’t. And a few days ago I discovered that another two of the original capacitors left on the motherboard look like a finger stung by a bee.

That got me mad. Really mad. I definitely ain’t gonna patch this motherboard for a third time. It’s time to stop trying to resurrect the dead and let the priest light a candle.

Darned capacitors.

I was planning to replace the core components of my PC with modern stuff — a new motherboard, an Intel Core 2 Duo processor, some DDR2 memory and probably a reasonable video card on PCI Express. That’d give me a lot of juice, less heat, less noise, and a bundle of features such as 10 USB2 ports on-board and Serial ATA 300. It looked like a big investment and I was waiting for prices to drop, using the old PC in the mean time. After all, I only get to spend maybe 6 to 8 hours per week at my home computer these days, so $1000 sitting in an unused computer would be a stupid idea.

But the old PC went belly-up, thanks to the effin’ faulty capacitors. And I needed an immediate solution. So I bought a cheap motherboard for Socket A (pretty much the only model I could still find in stock anyway), which will keep me running for some time. In need of space, I also bought a new 320 GB hard drive on PATA, so the pressure of SATA is gone for now.

Effin’ capacitors.

On a side note, yesterday I bought a second hand Dell OptiPlex G150, a nice Pentium III in a slim case, to become a flexible file server (and maybe a print server, and media center, and whatever else I want to throw at it — like, running a couple more virtual machines on it with Microsoft Virtual PC). Its inner workings are wonderful, the case is so well thought and the airflow keeps the system cool with one fan for video card, hard drive and power supply. Everything inside is made by Foxconn and labeled as such. The motherboard is a little smaller than mATX form factor, and has only 5 capacitors on it.

They’re swollen.

*sigh*

Now, does anyone want to buy an old Epox 8K3A motherboard (Socket A, VIA KT333 & 8233 chipset, 266 MHz maximum processor FSB and 333 MHz maximum memory frequency) which has gone through surgery twice and still needs (at least) a third intervention?