Archive for the 'Tips & tricks' Category

Scheduled automatic hard drive defragmentation for Windows Server 2003

Friday, 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.

Networking basics, tools and principles

Sunday, July 9th, 2006

One of my older interests, computer networking, has finally received a recent “upgrade” by rounding up my toolbox.

Previously in my toolbox: RJ11 and RJ45 crimping tools.
Added to the toolbox: 110 and Krone punch-down tools, intelligent cable tester with LCD display.
Near future needs: cable tracer/identifier, either purchased (kind of expensive and little used) or DIY (dirt cheap, more time involved, unprofessional look).
Long-term possible purchases: better cable tester, including Time Domain Reflectometer function to locate where a wire is interrupted. Expensive and not needed at this time.

With the new tools I was able to find out that the cables I installed in this apartment last summer were pretty badly done. Back then, I crimped the wall cable and, in one year, nearly half of the electrical connections were interrupted or intermittent. Now, after installing proper wall jacks and patch cables, only one pair of a cable is still interrupted somewhere in a wall, but it’s not influencing the network.

Why did I need all these tools and how are they used? Here’s a brief network cabling primer.

It all starts with intelligent wiring of your location. Think ahead of your needs and, if you’re still going to make a mess with running cables through walls, do it properly and with sufficient room to grow in the future without having to take the walls apart again. Find an out of the way, central location for the networking equipment; you’ll install a 19″ rack here, where the patch panel, switches and other equipment will be locked in. Determine where network connectors are needed now and where it might be a good idea to have them in the future. Figure out how to run the cables from the central location to each socket. Decide if the cables are far enough (at least one meter) from sources of electromagnetic interference (power wires, motors, fluorescent lights); if yes, use unshielded cable (UTP), otherwise go for shielded cable (FTP). If running cables over false ceiling tiles, you might need to use special cable type whose insulation doesn’t produce toxic fumes in case of fire.

Run CAT5e cable for each socket. Use “wall” cable for this, it has a single copper strand for each wire and, as a result, it’s pretty stiff. If ran horizontally, install supporting brackets one meter apart; the cable being rigid, it will support its own weight easily. If you tie cables together (with cable ties or whatever), don’t squeeze cables together too hard, let them slightly loose. Don’t bend cables at sharp 90 degrees, give them a small bend radius. Don’t pinch, tear, cut or punch cable insulation. Label all cables. Leave extra cable at each end before cutting it.

Hint #1: Run two network cables (CAT5e) and a voice cable (CAT3, one or two pairs, one pair per phone line) for each wall socket location. This will make it easy to double the number of computers installed and easily add/move phones around, or use the second cable in case something goes wrong with the first.

Wall cable doesn’t get crimped because the thin, metallic fins in the RJ45 connector can’t cut through the single copper strand in each wire, so they get bent and only make partial contact in most cases. The only kind of cable that gets crimped is “patch” cable, which has each wire made of several, thinner strands of copper wound together, giving flexibility to the cable and allowing the metallic fins in the connector to pass between these strands in each wire, ensuring better electrical connections.

Wall cable is connected at one end to a network socket mounted in or on a wall, and into a patch panel at the other end, where the central networking equipment is. Basically, each wire in the cable is punched through a metallic Y-shaped contact which cuts through the insulation. There are two types of connectors: 110 and Krone. Krone has the metallic contact at 45 degrees to the wire, while 110 has a right-angle position. Each type of connector needs a different punch-down tool. Decide which you want to use and buy the appropriate punch down tool, wall sockets and patch panel.

Note: Wall sockets with screws for wires look the same as Ethernet sockets, but they’re not; they are designed for ISDN telephone wires, and not appropriate for networking.

Hint #2: Get both kinds of punch-down tools if you want, they’ll be handy and not expensive. Some patch panels and wall sockets are dual, having connectors both for 110 and Krone. 110 is more widely used in telephone systems.

Decide on the color coding to use for connecting wires: TIA/EIA 568A or 568B. Connect wires to sockets, mount sockets in walls or apply them on walls, connect wires to the patch panel. Label each socket and connector and its corresponding port in the patch panel. If you used shielded cable, the shield foil will be a bit of pain, but you need to connect it as well — and all cables in the network must be shielded, otherwise it’s useless. Make sure you don’t untwist wire pairs for more than 2.5 centimeters (one inch).

Hint #3: Most people prefer 568B color scheme. It’s up to you, just be consistent so fault finding and upgrades/replacements are much easier and less time consuming.

Hint #4: Help yourself (and others) understand what port in the patch panel goes where, by using a simple naming convention. Number wall sockets and assign letters to each port. For a two-connector wall socket, name them 1A and 1B, for the next wall socket go with 2A and 2B, and so on. Keep numbers tidy, group them by location in the building. You could have a name like 245A, indicating left connector (A) on the wall socket number 5 in office/room/work area number 4 on 2nd floor. Leave room in the numbering system for growth, use sequential numbers only for small groups of outlets.

With cables connected to patch panel and wall sockets, test all cables at least with a cable tester, to make sure you have the right cables and labels, you have continuity and proper wire pairing. Professionals will go as far as test the signal quality, certify the wiring for certain speeds and guarantee performance of this infrastructure.

You should now have a patch panel (or more) with lots of ports connected to sockets throughout the building. It’s not surprising to have 48 ports wired up for a network that will start with 6 or 10 PCs, but with a high probability of increasing the computer infrastructure in a few years. The many ports gives you flexibility to move computers around, there’s always a network socket nearby, no need to run long cables across the floor and tell people “don’t trip over the cable” a hundred times a day.

A network switch is mounted in the rack. You’ll use short (30 centimeters), pre-made patch cables, to connect the ports in the switch with the ports in the patch panel corresponding to wall sockets being used. If the switch has management capabilities, make note which port is connected to which wall socket, so you know whose computer is connected to which switch port in order to assign access rights to the network. In the building, connect the computers to nearby wall sockets with pre-made patch cables — they come in various lengths: 1, 3, 5, 10 meters.

Voice cables connect to phone jacks in the office and something similar to a patch panel at the central location, from where other cables will make the connections to the PABX or the lines from the phone company.

So, there — all done. Notice that I haven’t used the crimping tools. That’s because they are normally used to crimp patch cables. It’s cheaper to just buy pre-made and certified patch cables to the desired length and color, than to buy a roll of cable and build your own cables. The crimping tools are handy in emergency situations, though.

Mozilla Firefox 1.0 released

Thursday, November 11th, 2004

I’m joining the crowd which announces that Mozilla Firefox, the lightweight yet ultra-powerful web browser from Mozilla, has finally reached version 1.0. It has a load of improvements and bug fixes (even if not all known bugs were actually fixed yet), it makes surfing more productive and more secure, and I can’t think of any reason why someone would use any other browser, especially Internet Explorer.

Firefox uses “extensions” to enhance its functions with third party software, and “themes” to change its appearance (like “skins” in Winamp). Note that older extensions and themes will probably not work with the newest version, so you will need to get the updated versions of those as well if you have used an older version of Firefox. The best way to upgrade is still saving the bookmarks (Bookmarks menu, Manage bookmarks, File menu, Export), uninstall the old version, then install the new one on the clean drive and import back the bookmarks (if needed).

To make tabbed browsing more efficient than the default tab behaviour, consider getting the Tabbrowser Extensions extension. The author’s website has the most recent version, unlike Mozilla Update site. Another useful extension is Download Manager Tweak which improves the download manager built into Firefox, but this extension has not been updated yet to work under Firefox 1.0 final. Keep an eye out for it, though.

As for the user interface, I like a clean appearance, not too colorful or intrusive; that’s why I settled for Bernie Zimmermann’s version of GrayModern theme. It’s simply a pleasure to look at, and it works under Firefox 1.0.

Give Firefox a try. It might seem “different” at first, but after you start to get used to it you will love the extra features over other browsers.