Tag Archives: network

This post is a collection of some of the more commonly used command line utilities when doing basic troubleshooting in a Windows domain environment.

To open a command window within a directory from Windows Explorer, hold the Shift key and right-click on the directory, then choose “Open command window here”.

cd

Displays the name of the current directory or changes the current folder.
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds.mspx?mfr=true

Used within a command window to change the current active directory, allowing navigation through the computer’s mapped drives and their directory structures.

Usage:

cd
Displays the current directory path.

cd
Moves to the root of the current drive.

cd /d e:
Moves to the E: drive from another drive. It’s also possible to move to a different drive by typing only the drive letter followed by a colon, ex: D:

cd..
Moves to the parent directory of the current directory (move up one directory toward the root).

cd “People to sue next”
Moves from the current directory into the subdirectory named “People to sue next”. A handy trick is to just type the first few characters of the directory name, and then hit the tab key to auto-complete the rest of the directory name from the first alphabetical match found, and even wrap it in double quotes if it contains spaces. For example, the same command as above can by typed: cd peop <tab>

If the current directory contains multiple matches for the characters typed, hitting tab again will cycle to the next match.

The tab method can be used more than once, to chain together a series of directories. For example, to move to the C:\Users\Public\Documents directory from a command prompt at the root of C:, one can type: cd u <tab> p <tab> d <tab> <tab> <enter>

dir

Displays a list of a directory’s files and subdirectories.
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/dir.mspx?mfr=true

Usage:

dir
Displays the directories and files in the current directory.

dir /s
Displays the directories and files in the current directory and all sub directories.

Dir can also be used to search for a file, and in many cases it works better than the Windows Explorer search.

dir c:\findme.txt /s
Displays a list of all instances of a file named “findme.txt” on the C: drive. It’s also possible to navigate to a location, such as the root of C:, and type: dir /s findme.txt to search that location and all subdirectories for a file named “findme.txt”.

Wildcards are allowed in the form of an asterisk. For example, type: dir c:\*.doc /s to search the C: drive for all files with a .doc or .docx extension (I’m not sure why it also locates .docx files, when there is no wildcard specified at the end of the extension, but it does).

Another command line utility for searching for files is where, but the syntax is slightly more complicated.

gpupdate

Refreshes local and Active Directory-based Group Policy settings, including security settings.
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/refrgp.mspx?mfr=true

If you absolutely must reapply all settings, you can use the /force switch. After reading about the difference between gupdate and gpupdate /force, I now feel that gupdate is sufficient to reapply group policy nearly all of the time, and the /force switch shouldn’t automatically be used.

Usage:

gpupdate
Reapplies group policy.

gpresult

Displays Group Policy settings and Resultant Set of Policy (RSOP) for a user or a computer.
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds.mspx?mfr=true

Usage:

gpresult /r
Displays RSoP summary data, which includes the last time group policy was applied, from which server group policy was applied, and the groups for which the current user is a member.

gpresult /h gpreport.html
Generates a report of the applied group policy settings and saves it in HTML format as a file named gpreport.html. When generating a report as a user that is not a local administrator, either supply a full path to a valid location for gpreport.html, or navigate to a location (like the Public Documents directory) before running the command, or else the utility may be unable to create the report due to insufficient rights to the current directory.

ipconfig

Displays all current TCP/IP network configuration values and refreshes Dynamic Host Configuration Protocol (DHCP) and Domain Name System (DNS) settings. Used without parameters, ipconfig displays the IP address, subnet mask, and default gateway for all adapters.
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ipconfig.mspx?mfr=true

Usage:

ipconfig
Display the computer’s IP address and default gateway, for each network adapter.

ipconfig /all
Displays full TCP/IP information, including the MAC address, DHCP server, and DNS servers, for each network adapter.

net use

Connects a computer to or disconnects a computer from a shared resource, or displays information about computer connections. The command also controls persistent net connections. Used without parameters, net use retrieves a list of network connections.
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/net_use.mspx?mfr=true

Usage:

net use
Lists all of the computer’s connections (mapped network drives).

net use e: \\ComputerName\ShareName
Maps the E: drive to the ShareName shared resource on the ComputerName computer. To map the local E: drive to the C: drive (which is a hidden share) of a remote machine named Loomer, type: net use e: \\loomer\c$

net use e: /delete
Removes the connection currently mapped to the local E: drive.

If you are connecting to a network share that your regular account does not have rights to access, you will be prompted for a username. You will need to also supply the domain, ex: domainusername

nslookup

Displays information that you can use to diagnose Domain Name System (DNS) infrastructure.
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/nslookup.mspx?mfr=true

Usage:

nslookup <ipaddress or computername>
Queries the local computer’s default DNS name server for information on the specified IP address or computer name. Supply either piece of information and nslookup will return both pieces. It’s also possible to specify a particular DNS name server to be queried, which is useful when troubleshooting whether DNS is propagating/replicating correctly.

ping

Verifies IP-level connectivity to another TCP/IP computer by sending Internet Control Message Protocol (ICMP) Echo Request messages. The receipt of corresponding Echo Reply messages are displayed, along with round-trip times. Ping is the primary TCP/IP command used to troubleshoot connectivity, reachability, and name resolution.

You can use ping to test both the computer name and the IP address of the computer. If pinging the IP address is successful, but pinging the computer name is not, you might have a name resolution problem.
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ping.mspx?mfr=true

Usage:

ping <ipaddress or computername>
Makes four attempts to contact the computer at the specified IP Address or with the specified computer name, and reports back whether the machine could be contacted and the time taken for the request to travel to the remote computer, be acknowledged, and the acknowledgement received by the local computer.

ping <ipaddress or computername> -t
Repeatedly attempts to contact the remote computer until interrupted by pressing Ctrl+Break or Ctrl+C. This is sometimes called a persistent ping.

systeminfo

Displays detailed configuration information about a computer and its operating system, including operating system configuration, security information, product ID, and hardware properties, such as RAM, disk space, and network cards.
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/systeminfo.mspx?mfr=true

The systeminfo command also reveals installed hotfixes and some information about the computer that isn’t readily available in Device Manager or other MMC Snap-ins, such as the BIOS version.

Usage:

systeminfo
Displays information about the local computer.

systeminfo /s computername /u domainuser
Displays information about a remote computer named computername.

systeminfo /s computername | find “System Model:”
Retrieves information about a remote computer named computername, but pipes the output of systeminfo to the find command, which returns only the line containing the string “System Model:”. This output in the command window shows only “System Model:” followed by the model of the remote computer.

The systeminfo report can be sent to a text file, ex: systeminfo > systeminforeport.txt

Bonus commands

getmac

Returns the media access control (MAC) address and list of network protocols associated with each address for all network cards in each computer, either locally or across a network.
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/getmac.mspx?mfr=true

Usage:

getmac /v
Shows MAC addresses for the local computer.

getmac /s computername /u domainusername /v
Shows MAC addresses for a remote computer named computername while authenticating as a different user.

(Need to test this.)

msg

Sends a message to a user (this may be turned off in many environments). Run msg /? for usage information.

Here’s an example script demonstrating how a publicly accessible home page can leverage JavaScript to detect whether a machine is on a corporate intranet and then redirect the browser to an intranet page.

In the example, http://alephstudios.com acts as the corporate intranet site that is not accessible from outside the company’s network, and //ardamis.com acts as the publicly accessible site, which can be accessed both from within and outside the corporate network.

The browser is set to use a page on the public //ardamis.com site which includes some JavaScript that attempts to load an image from a location on the company intranet. If the image can be successfully loaded by the browser, we have establishe that the machine is on the internal network. The browser can then be redirected via JavaScript to an appropriate intranet page. Otherwise, the browser is redirected to an Internet page.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Intranet Detection Script</title>
<script type="text/javascript">
<!--

var internalURL = 'http://alephstudios.com';
var publicURL = '//ardamis.com';
var detectionCounter = 0;
var detectionTimeOut = 5;
var detectionImage = 'http://alephstudios.com/testing/intranet/transparent.gif?' + (new Date()).getTime();
var detectionElement = document.createElement('img');
detectionElement.src = detectionImage;

function detectIntranet() {
    detectionCounter = detectionCounter + 1;
    //  alert('Attempt ' + detectionCounter + ': Sniffing intranet connection by loading an internal resource at ' + detectionImage);
    if (detectionElement.complete) {
        if (detectionElement.width > 0 && detectionElement.height > 0) {
            //      alert('Attempt ' + detectionCounter + ': The intranet resource was loaded!');
            window.location = internalURL;
        } else {
            //      alert('Attempt ' + detectionCounter + ': The intranet resource could not be loaded!');
            window.location = publicURL;
        }
    } else {
        if (detectionCounter < detectionTimeOut) {
            setTimeout("detectIntranet()", 1000);
            //      alert('Attempt ' + detectionCounter + ': Still trying to load: ' + detectionImage);
        } else {
            alert('Attempt ' + detectionCounter + ': Gave up trying to load: ' + detectionImage);
            //	  window.location = publicURL;
        }
    }
}

window.onload = function () {
    detectIntranet();
}

//-->
</script>
</head>

<body>
</body>
</html>

Setting up an intranet detection/redirection page as the browser’s home page allows IT to display an intranet page while the device is on the network and an Internet page when the device is off the network.

I’m in the middle of troubleshooting a printing problem that has arisen with our in-development Windows 7 image. We’re running 64-bit Windows 7 Enterprise with Office 2010 and using the HP Universal Print Driver for Windows PCL6 version 5.4.0 dated 1 Dec 2011 (the current version). The printer driver is installed on a Windows server using default settings and the printer connections on the workstations are created either as per-machine connections by running printui.exe /ga or as per-user connections by running the Find Printers wizard in an Office application. The printers themselves are HP 4250n and HP P4015 models with relatively up-to-date firmware.

The problem is that certain print jobs produce many pages of apparent gibberish instead of the intended file or email message. The gibberish pages begin like this:

"
 @PJL SET JOBATTR="JobAcct8=USERNAME"
                                     @PJL SET JOBATTR="JobAcct9="
                                                                 @PJL SET RET=OFF

I’ve done some research into the lines beginning @PJL, and my understanding is that PJL (Printer Job Language) commands are part of the standard job header output from the Universal Printer Driver, and that when everything is working normally, they are processed by the printer as instructions instead of printed as text.

For more reading about PJL commands, I can recommend the page at: http://www.sxlist.com/techref/language/pcl/lj1686.htm

Almost immediately, I was able to rule out the per-machine connections as being the cause, as the problem also occurred on per-user connections. The same files that printed problematically to the networked HP printers printed normally to locally-installed printers using non-UPD PCL 6 drivers. It seemed logical to pursue this as a driver-related problem.

What is PCL 6

It’s probably worth pausing here for a bit of explanation of PCL 6.

The Enhanced PCL XL or PCL6 driver that is included with the HP LaserJet printers provides enhanced WYSIWYG and enhanced performance with application support over the Standard (PCL5e) driver. PCL XL is a new page description language by HP that is part of PCL6 and is closer to GDI, which many applications use. Less translation takes place by the driver, which means increased WYSIWYG capabilities and better performance with applications that support escapes implemented by the Enhanced driver. The output from the Enhanced (PCL XL) driver may not be the same as the output from the Standard driver. If the output is not as expected, choose the Standard (PCL5e) driver instead.
What is the Enhanced PCL XL or PCL6 Driver?

The part that catches my eye is “better performance with applications that support escapes implemented by the Enhanced driver”. Are we encountering applications that do not support escapes?

Eliminating possible causes

Possible causes of the PJL commands being output as text include the driver not prefixing the PJL statements (at the beginning of each job) with a Universal Exit Language (UEL) escape sequence. (http://www.tek-tips.com/viewthread.cfm?qid=1618494)

To rule this out, one can use the “print to file” option in the print dialog box to produce a file that contains the instructions that would be sent to the printer.

Choose File | Print in your application, then check the “Print to file” box in the print dialog box. (In Office 2010, the Print Options button under the available printers menu displays the print dialog box.) Choose a name for the .prn file and save it somewhere, then open the resultant *.prn file in something that displays escape characters, such as Notepad++ (or even Notepad). The first character should be an escape character, and the first line of text will begin something like this:

{ESC}%-12345X

If the PJL initialization command looks correct, it’s possible that the printer is not properly configured to accept PJL commands. Older printers may not be PJL-aware, but I knew our printers to work fine with older 32-bit HP UPDs installed on our Windows XP machines. The ‘Personality’ attribute on HP printers can be checked by going to the printer’s web admin panel and browsing to Settings | Configure Device | System Setup. Setting the Personality to PS is probably going to cause problems, but either Auto or PCL should work. I confirmed that our printers were set to Auto, further ruling out the printers themselves as the cause of the problem.

I next looked at disabling the advanced features of the driver (a little skeptically, I’ll admit). This can be done by going into the printer’s properties and unchecking the “Enable advanced printing features” box on the Advanced tab. (http://h30499.www3.hp.com/t5/Print-Servers-Network-Storage/12345X-PJL-Printing-on-Dot-Matrix-Printers/td-p/1132391) I was curious about how this affected the job sent to the printer – would the entire series of JPL commands be removed?

To test, I unchecked the “Enable advanced printing features” and printed an email message to a *.prn file, then checked the box and printed the same email to a second *.prn file, then compared the two files. The only difference in the PJL commands was that “@PJL SET SEPARATORPAGE=OFF” was present with advanced printing features enabled, and absent with advanced printing features disabled.

I found the separator page line to be an interesting difference, as banner pages/separator pages had been suggested as a possible cause, but our drivers were not configured to print separator pages. (http://www.oasq.com/PJL-SET-JOBATTR-thread-252568-1-1.html)

So, that’s where the issue currently stands. I’m waiting to see if turning off advanced printing features has any effect. To be thorough, I need to test whether the UPD PS driver prints without error and whether the problem continues with a printer connected via TCP/IP and with a manually installed driver. I can also bring the printers up to the latest version of the firmware, although this would be a less satisfactory resolution, as we have a variety of printer models and not all of them have firmware updates available.

Update 17 Feb. 2012

The Application event log on the print server contains a number of errors, though we’re unsure of whether there is a direct correlation between the errors and attempts by Windows 7 users to print, or jobs in the spooler being processed, or any other activity.

Description:
Faulting application name: PrintIsolationHost.exe, version: 6.1.7600.16385, time stamp: 0x4a5bd3b1
Faulting module name: hpzuiwn7.dll, version: 0.3.7071.0, time stamp: 0x4a5bdfcb
Exception code: 0xc0000005
Fault offset: 0x00000000000d6971
Faulting process id: 0x900
Faulting application start time: 0x01ccea9860e17377
Faulting application path: C:\Windows\system32\PrintIsolationHost.exe
Faulting module path: C:\Windows\system32\spool\DRIVERS\x64\3\hpzuiwn7.dll
Report Id: 3eaa21e6-568c-11e1-b7a4-005056a50027

It certainly does look like the 64-bit HP driver is at fault here. More searching has turned up a number of reports of this error with HP’s UPD PCL6 driver, going back to 2010.

Because we have a small number of Windows 7 users, we’re removing the network printers from the Windows 7 machines temporarily, to see if the server stabilizes.

Update 21 Feb. 2012

We were able to take a closer look at the print server today. We searched the registry for hpzuiwn7.dll and noted the printers that had this DLL listed among the supporting files. Many, but not all, of the printers included this DLL. We also reviewed the printers in Print Management and made an odd discovery. There seemed to be two varieties of the model-specific PCL 6 driver in use: one is named “HP LaserJet 4250 PCL 6” and the other is “HP LaserJet 4250 PCL6“. The difference in the naming is that the later driver has a space between PCL 6. While most of the printers used the UPD, a handful were using one of the model-specific drivers. When we looked at the Additional Drivers, we found that one of them had only the 64-bit version available. I expect that only 32-bit workstations are printing to those printers, so I’m not sure how they even functioned, but it would seem that the next step would be to either add the matching 32-bit drivers for that model printer or change the assigned driver to UPD PCL 6. I suspect that we were not diligent enough about exactly matching the printer driver names (let alone the version numbers) when we were installing drivers on the server.

Update 1 Mar. 2012

After installing the missing 32-bit driver that complemented the stray 64-bit driver, all of the printing problems, including the error messages in the Application log on the server, have subsided.

In the VBScript example below, I’m using the Icacls.exe utility to assign modify permissions to the D:\Test folder for the user Oliver on the LOOMER domain (or local machine). The script includes as comments some good resources on the subject.

' http://support.microsoft.com/kb/919240
' http://technet.microsoft.com/en-us/magazine/2009.07.geekofalltrades.aspx
' http://timbolton.net/2010/06/23/icacls-changing-permissions-on-files-and-folders/

Dim strFolder, strUser, strDomain

strFolder = "D:\Test"
strUser = "Oliver"
strDomain = "LOOMER"

SetPermissions
	
Function SetPermissions()
	Dim intRunError, objShell, objFSO

	Set objShell = CreateObject("Wscript.Shell")
	Set objFSO = CreateObject("Scripting.FileSystemObject")
	If objFSO.FolderExists(strFolder) Then
		intRunError = objShell.Run("icacls " & strFolder & " /inheritance:r /grant:r " & strDomain &"\" & strUser & ":(OI)(CI)M ", 2, True)
		
		If intRunError <> 0 Then
			Wscript.Echo "Error assigning permissions for user " & strUser & " to folder " & strFolder
		End If
	Else
		Wscript.Echo "Error: folder " & strFolder & " does not exist"
	End If
End Function

This script is a work-in-progress. To be considered complete, I want it to be able to create multiple directories and assign them permissions. For extra credit, I want it to be able to accept as input a list of usernames from a text file and iterate through them, creating folders where necessary and assigning them permissions.

As part of a migration from Windows XP to Windows 7, I was asked to come up with a way to export the network printers installed on the XP machines such that they could be reinstalled on the Windows 7 machines. We did not want to capture local printers (printers installed via TCP/IP or connected via USB) or virtual printers (like the Adobe PDF virtual printer or the Microsoft XPS Document Writer). I thought that migrating the printers was less attractive because the source machines are 32-bit Windows XP but the destination machines are 64-bit Windows 7 and the drivers are therefore different.

There are a number of ways to export print queues, printer settings, and printer ports, but for my purposes, I decided that all I wanted was to determine the name of each printer (eg.: \\SERVER\Printer) on the XP machine, export that to a text file on a network share, and then run PrintUI.exe /ga on the Windows 7 machine, looping through the lines from the text file as input.

(Check out the Printer Migration wizard by launching PrintBrmUI.exe, or the command line version %WINDIR%\System32\Spool\Tools\Printbrm /?, for alternatives to printui.exe.)

As an added benefit, I’m also exporting the name of the default printer so that it can be set programatically in the new environment.

The code is a work in progress, but I hope it helps get your started.

The VBScripts

Here are the scripts I’ve pieced together.

exportPrinters.vbs

The exportPrinters.vbs script creates two text files in H:\PRINTERS, so adjust your path accordingly.

Const ForWriting = 2

Set objNetwork = CreateObject("Wscript.Network")

strName = objNetwork.UserName
strDomain = objNetwork.UserDomain
strUser = strDomain & "\" & strName

'strText = strUser & vbCrLf

strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")


' Export a list of network printers to a text file

Set colPrinters = objWMIService.ExecQuery _
    ("Select * From Win32_Printer Where Local = FALSE")

For Each objPrinter in colPrinters
    strText = strText & objPrinter.Name & vbCrLf
Next

Set objFSO = CreateObject("Scripting.FileSystemObject")

strFolder = "H:\PRINTERS"

If Not objFSO.FolderExists(strFolder) Then
    objFSO.CreateFolder(strFolder)
End If

Set objFile = objFSO.CreateTextFile _
    ("H:\PRINTERS\printers.txt", ForWriting, False)

objFile.Write strText

objFile.Close


' Export the default printer separately

Set colPrinters = objWMIService.ExecQuery _
    ("Select * From Win32_Printer Where Default = TRUE")

For Each objPrinter in colPrinters
    strText = objPrinter.Name
Next

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objFile = objFSO.CreateTextFile _
    ("H:\PRINTERS\default.txt", ForWriting, False)

objFile.Write strText

objFile.Close

importPrinters.vbs

Note that, if your users in Windows 7 are not administrators, you will need to run the script as an administrator (there are a few different ways) or else you’ll get a UAC prompt for each printer installation and the restarting of the print spooler.

Again, watch the paths. This is a home-grown script for my specific environment.

Option Explicit

'This script must be run with administor privileges
'If it is not run with administrator privileges, it will launch a UAC prompt for each printer as it loops through the list
'Here's an interesting article about running VBS as a different user:
'http://blogs.technet.com/b/heyscriptingguy/archive/2006/04/28/how-can-i-use-the-runas-command-to-run-a-script-under-alternate-user-credentials.aspx

'For example:
'runas /profile /user:[username]\[password] "cscript.exe \"F:\Printer Driver Research\Automation\printers-import.vbs"\"

Dim objNetwork, strComputer, strName, strFolder, objFSO, strTextFile, strData, strLine, arrLines, strRunCmd, WshShell
CONST ForReading = 1

'Create a Network Object
Set objNetwork = CreateObject("Wscript.Network") 

'Get the local machine name from the Network Object
strComputer = objNetwork.ComputerName 

'Get the user's username from the Network Object
strName = objNetwork.UserName

'Create a File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

'Save the name of the text file as a variable 
'Note that the script must be run as an administrator and that invoking the script with
'Run As causes the script to run as though it's located in the same directory as "%SystemRoot%\System32\WScript.exe"
'Hence the need to pass the full path to the printers.txt file
strTextFile = "H:\PRINTERS\printers.txt"

'Open the text file - strData now contains the whole file
strData = objFSO.OpenTextFile(strTextFile,ForReading).ReadAll

'Split the text file into lines
arrLines = Split(strData,vbCrLf)

'Initialize the wshShell
Set WshShell = WScript.CreateObject("WSCript.shell")

'Step through the lines
For Each strLine in arrLines

    If Len(strLine) > 0 Then
		'Only run the process on lines that aren't blank
		
'		strRunCmd = "rundll32 printui.dll,PrintUIEntry /ga /c\\" & strComputer & " /n" & strLine & ""
		strRunCmd = """printui.exe"" /ga /q /c\\" & strComputer & " /n" & strLine & ""
		
		'Echo back the command to be run
'		WScript.Echo strRunCmd

		'This launches printui.exe
'		strRunCmd = """printui.exe"""

		'Run the command, display the window, and wait for the command to complete before continuing
		Dim result
		result = WshShell.Run(strRunCmd, 1, True)
		
'		WScript.Echo result
		
		'Write to the application log that the printer was installed
		If result = 0 Then 
			WshShell.LogEvent 0, "User: " & strName & " - Event: attempted to install printer " & strLine & " with [" & strRunCmd & "] (success unknown)"
		End If
		
'		WScript.Echo "Processed printer: " & strLine
    End If

Next

'Cleanup
Set objFSO = Nothing

'Wait 10 seconds
WScript.Sleep 10000

'Restart the Print Spooler
RestartService "Print Spooler", True

Sub RestartService( myService, blnQuiet )
' This subroutine restarts a service
' Arguments:
' myService     use the service's DisplayName
' blnQuiet      if False, the state of the service is displayed
'               every second during the restart procedure
'
' Written by Rob van der Woude
' http://www.robvanderwoude.com

    ' Standard housekeeping
    Dim colServices, colServicesTest, objService
    Dim objServiceTest, objWMIService, strQuery, strTest

    ' Create a WMI object
    Set objWMIService = GetObject( "winmgmts:\\.\root\CIMV2" )

    ' Query the services for "our" service
    strQuery = "SELECT * FROM Win32_Service WHERE DisplayName='" & myService & "'"
    Set colServices = objWMIService.ExecQuery( strQuery, "WQL", 48 )

    ' Loop through the "collection" of returned services
    For Each objService In colServices
        ' See if we need to tell the user we're going to stop the service
        If Not blnQuiet Then
            WScript.Echo "Stopping " & myService
        End If

        ' Stop the service
        objService.StopService

        ' Wait until the service is stopped
        Do Until strTest = "Stopped"
            ' Create a new object for our service; this work-around is required
            ' since otherwise the service's state information isn't properly updated
            Set colServicesTest = objWMIService.ExecQuery( strQuery, "WQL", 48 )

            ' Loop through the "collection" of returned services
            For Each objServiceTest In colServicesTest
                ' Check the service's state
                strTest = objServiceTest.State
                ' See if we need to show the progress
                If Not blnQuiet Then
                    WScript.Echo "State: " & strTest
                End If
                ' Wait 1 second
                WScript.Sleep 1000
            Next

            ' Clear the temporary object
            Set colServicesTest = Nothing
        Loop

        ' See if we need to tell the user we're going to (re)start the service
        If Not blnQuiet Then
            WScript.Echo "Starting " & myService
        End If

        ' Start the service
        objService.StartService

        ' Wait until the service is running again
        Do Until strTest = "Running"
            ' Create a new object for our service; this work-around is required
            ' since otherwise the service's state information isn't properly updated
            Set colServicesTest = objWMIService.ExecQuery( strQuery, "WQL", 48 )

            ' Loop through the "collection" of returned services
            For Each objServiceTest In colServicesTest
                ' Check the service's state
                strTest = objServiceTest.State
                ' See if we need to show the progress
                If Not blnQuiet Then
                    WScript.Echo "State: " & strTest
                End If
                ' Wait 1 second
                WScript.Sleep 1000
            Next

            ' Clear the temporary object
            Set colServicesTest = Nothing
        Loop
    Next
End Sub

setDefaultPrinter.vbs

Finally, we want to set the default printer. The printer will have to already exist (obviously). If you’ve just fired off the printui.exe /ga command to install the printer, it won’t be available until the print spooler is restarted. So wait a minute or two before running the script.

Option Explicit

Dim objNetwork, strComputer, objFSO, strTextFile, strData, strLine, arrLines, strRunCmd, wshShell
CONST ForReading = 1

'Create a Network Object
Set objNetwork = CreateObject("Wscript.Network") 

'Get the local machine name from the Network Object
strComputer = objNetwork.ComputerName 

'Save the name of the text file as a variable 
strTextFile = "H:\PRINTERS\default.txt"

'Create a File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

'Open the text file - strData now contains the whole file
strData = objFSO.OpenTextFile(strTextFile,ForReading).ReadAll

'Split the text file into lines
arrLines = Split(strData,vbCrLf)

'Initialize the wshShell
Set wshShell = WScript.CreateObject ("WSCript.shell")

'Step through the lines
For Each strLine in arrLines

    If Len(strLine) > 0 Then
		'Only run the process on lines that aren't blank
		
'		strRunCmd = "rundll32 printui.dll,PrintUIEntry /y /c\\" & strComputer & " /n" & strLine & ""
		strRunCmd = """printui.exe"" /y /c \" & strComputer & " /n """ & strLine & """"
'		wscript.echo strRunCmd
		wshShell.Run strRunCmd
		
'		wscript.echo "Processed printer: " & strLine
    End If

Next

'Cleanup
Set objFSO = Nothing

As the migration proceeds, I’ll come back and tweak the scripts. Please feel free to leave comments and suggestions.

Thanks go to Rob van der Woude for his terrific Command Line Printer Control page, as well as many others.

I’m trying to find a way to save some Xbox 360 achievements that I’ve earned while my console was offline. Typically, just connecting to Xbox Live will sync up your gamertag and the offline achievements will be added to you profile. This works because, usually, the gamertag is associated with a single Xbox 360, which goes offline and then back online. My situation is different, and it seems like I’m going to lose my offline achievements.

The set up

I have a single gold account and two Xbox 360 consoles. One of these consoles is always online and is used exclusively for watching Netflix (because the drive tray is broken). The other console works fine for games, but is physically located where wired Ethernet isn’t available, and I haven’t purchased a wireless adapter. In order to get the same gamertag on both consoles, I used the recover gamertag feature to bring it down to the online console. This means that the Netflix gamertag is regularly connecting to Xbox Live while my gaming is done on the same gamertag, but offline.

Microsoft doesn’t seem to want to support this sort of arrangement, as it appears that gamertags are associated with individual Xbox consoles and that only the last-to-be-connected gamertag is seen as legit.

The problems

The first problem I’m facing is how to get all of these achievements that were earned offline sync’d up with my Live profile. One might reasonably think that simply connecting the offline Xbox to Xbox Live and logging in would do this, but Live sees the account as invalid (presumably because the account associated with the other box has connected more recently). Upon connecting to Xbox Live, I’m prompted to recover my gamertag, which I know from experience will erase my offline achievements (I’ll get the gamertag as it exists on the online console – which will also render the gamertag on the online console invalid).

I also tried to use a USB flash drive to move my gamer profile from the offline box to the online box. The move itself was successful, but when I tried to connect to Live, it again found the account to be invalid and invited me to recover my gamertag. I was able to move the gamer profile back to the USB drive, remove the drive, and then recover the online gamertag in order to keep using Netflix, but I was back to square one.

I haven’t yet tried moving the offline console’s hard drive with the gamertag to the online console. As of right now, this is the only thing I can think to try.

The second problem I’m facing is that the offline Xbox doesn’t yet have the new dashboard and some of my games have updates available that are supposed to fix some bugs. I’ve read that it should be possible to get these updates by creating a silver account and logging into Xbox Live under that account. That would be somewhat helpful, but unnecessary if I can solve the first problem.

Autonegotiation

Network autonegotiation is easily misunderstood. Consider two 10/100Mb devices attached to one another – a PC connected to a router. For each of these devices, it’s possible to configure the connection to use either 1) a fixed speed and duplex or 2) to negotiate the optimal shared speed and duplex with whatever it is connecting to. What is not intuitive is that both devices must be configured with the same settings. The connection will suffer a performance hit, or may not work at all, if the two devices are configured differently.

A common misconception about autonegotiation is that it is possible to manually configure one link partner for 100 Mbps full-duplex and autonegotiate to full-duplex with the other link partner. In fact, an attempt to do this results in a duplex mismatch. This is a consequence of one link partner autonegotiating, not seeing any autonegotiation parameters from the other link partner, and defaulting to half-duplex.

http://www.cisco.com/en/US/products/hw/switches/ps4324/products_tech_note09186a0080094713.shtml#auto_neg

If both devices are configured to autonegotiate speed and duplex, then each will attempt to make the best possible connection among the possibilities they have in common. However, if one of the devices is set to use a fixed speed and duplex and the other device is set to autonegotiate, the autonegotiating device can determine the speed but not the duplex of the other device and so falls back to its default duplex mode. In the case of Cisco switches, the default duplex mode is half-duplex.

…it is possible for a[n autonegotiating] link partner to detect the speed at which the other link partner operates, even though the other link partner is not configured for auto-negotiation. In order to detect the speed, the link partner senses the type of electrical signal that arrives and sees if it is 10 Mb or 100 Mb.

It is not possible to detect the correct duplex mode in the same method that the correct speed can be detected. In this case, the […] port of [the autonegotiating] switch […] is forced to select the default duplex mode. On Catalyst Ethernet ports, the default mode is auto-negotiate. If auto-negotiation fails, the default mode is half-duplex.

http://www.cisco.com/en/US/tech/tk389/tk214/technologies_tech_note09186a0080094781.shtml

Half-duplex as a default duplex mode is not unique to Cisco switches. Below is a link to an article on www.dell.com written by Rich Hernandez, a senior engineer with the Server Networking and Communications Group at Dell, that contains a table summarizing “all possible combinations of speed and duplex settings, both on 10/100/1000-capable switch ports and on NICs.” Included are combinations that would yield no link or link fail conditions, as well as combinations that would yield a duplex mismatch.

http://www.dell.com/content/topics/global.aspx/power/en/ps1q01_hernan?c=us&cs=555&l=en&s=biz

The importance of using identical settings on both sides of a network connection is stressed in a KB article from www.symantec.com with information on how an autonegotiating port may report that it has established a full-duplex connection with a NIC configured for 100MBs/Full, but in fact is communicating at less than expected capacity.

Only by explicitly setting both sides of the link to the same duplex mode would the link work flawlessly.

http://www.symantec.com/business/support/index?page=content&id=TECH87827

Understanding link data errors

The page at the link below contains two tables that explain the various errors and counters logged by a network switch and the possible causes.

http://www.cisco.com/en/US/products/hw/switches/ps708/products_tech_note09186a00800a7af0.shtml#ustand

Troubleshooting Ethernet Collisions

Collisions may appear to indicate communication problems with a network connection, but as a technote from cisco.com states, collision counters alone are not indicative of network problems.

…collisions are a way to distribute the traffic load over time by arbitrating access to the shared medium. Collisions are not bad; they are essential to correct Ethernet operation.

There is no set limit for “how many collisions are bad” or a maximum collision rate.

In conclusion, the collisions counter does not provide a very useful statistic to analyze network performance or problems.

http://www.cisco.com/en/US/products/hw/modules/ps2033/products_tech_note09186a008009446d.shtml

Late Collisions

When a collision is detected by a station after it has sent the 512th bit of its frame, it is counted as a late collision.

The station that reports the late collision merely indicates the problem; it is generally not the cause of the problem. Possible causes are usually incorrect cabling or a non-compliant number of hubs in the network. Bad network interface cards (NICs) can also cause late collisions.

http://www.cisco.com/en/US/products/hw/modules/ps2033/products_tech_note09186a008009446d.shtml

I just picked up an old Dell Precision 690 workstation, which I intend to develop into a file server, a Windows IIS server, and an Ubuntu LAMP server. This monster was built in 2006, but it still has some neat specs and tons of capacity (7 PCI slots, 4 hard drive bays, etc…), should I want to expand further.

Dell Precision 690

Dell Precision 690 Workstation

The main specs

CPU: Dual Core Intel Xeon 5060 3.2GHz, 4M Cache, 1066 MHz FSB
RAM: 2GB DDR2 PC2-5300, CL=5, Fully Buffered, ECC, DDR2-667
HD: SAS Fujitsu MAX3073RC 73GB, 15000 RPM, 16MB Cache
Video: Nvidia Quadro NVS 285 PCI-Express, 128MB

This is not a normal tower

Right away, the size of this thing suggests it isn’t a normal tower. It’s about up to my knee and weights 70 lbs. It feels like it’s made with heavier gauge steel than the typical chassis, but that may be me projecting.

I immediately shopped around for more RAM, obviously. 2GB seems a little thin, even by 2006 standards, when considering the way everything else is high-end. The mainboard has 8 slots and supports up to 32GB, but I figure 6GB is a safe place to start.

The workstation has three enormous fans, like, big-as-your-hand big. Running it with the chassis open causes some sort of thermal protection system to kick in and it spins the fans up to the point that they were blowing stuff on the floor half-way across the room.

The CPU has a big, passive heat sink with six copper pipes and sits between two of those fans. I’m tempted to buy a second CPU, but I’ll hold off.

I’m still on the fence about the SCSI drive. It should be super fast, but I’m a little spoiled by the SSD in my machine at work, so it’s hard to get excited about a mechanical drive, even one running at 15k RPM.

The Nvidia Quadro card is also fanless, and has a bizarre DMS-59 connector. An adapter converts the DMS-59 connector into two DVI outputs.

Typically, your ISP provides DNS services. In an ideal world, this would work well, as your ISP’s DNS server ought to be geographically close to your machine and should be able to perform look ups quickly. However, there are a number of reasons why you might want to use a public DNS server instead of your ISP’s server. The two big public DNS servers are OpenDNS and Google Public DNS.

OpenDNS

The OpenDNS nameserver IP addresses are:

  • 208.67.222.222
  • 208.67.220.220

http://www.opendns.com/support/article/197

You can confirm that you are using OpenDNS as your DNS resolution service by visiting http://www.opendns.com/welcome/.

Google Public DNS

The Google Public DNS nameserver IP addresses are:

  • 8.8.8.8
  • 8.8.4.4

http://code.google.com/speed/public-dns/docs/using.html

Speed test

So which DNS servers are faster for you?

Try out namebench. It hunts down the fastest DNS servers available for your computer to use. (For Mac OS X, Windows, and UNIX.)

http://code.google.com/p/namebench/

Using OpenDNS to filter (whitelist/blacklist) content

If you have an account with OpenDNS, you can whitelist and blacklist IP addresses. A free account allows you to whitelist or blacklist 25 addresses; paid accounts allow more.

  1. Create an account at OpenDNS.
  2. Set up a network for your physical location (your current IP address).
  3. Configure your machine to use the OpenDNS servers.
  4. Install the client software for updating a dynamic IP in an OpenDNS network – https://support.opendns.com/entries/23282614-Where-do-I-download-an-OpenDNS-Dynamic-IP-updater-client-.

Technically more sophisticated users may discover that manually setting the DNS servers on a computer allows that computer to circumvent the OpenDNS filtering. To prevent a machine from bypassing the OpenDNS filtering, you could configure the DNS servers directly on the router and then block all outgoing DNS requests to all DNS servers except the OpenDNS servers.

OpenDNS system status

It’s a good idea to be able to check the condition of your DNS server.

The OpenDNS system status page’s IP address is http://208.69.38.170/.

Seriously restricting internet access

What I really want to do is severely restrict internet access on a single machine on my LAN. For this machine, I want to manage a small whitelist of domains and block access to everything else. OpenDNS doesn’t seem to offer this type of functionality.

I’ve written a few tutorials lately on how to reduce page load times. While I use Google’s Page Speed Firefox/Firebug plugin for evaluating pages for load times, there are times when I want a second opinion, or want to point a client to a tool. This post is a collection of links to online tools for testing web page performance.

Page Speed Online

http://pagespeed.googlelabs.com/

Google’s wonderful Page Speed tool, once only available as a Firefox browser Add-on, finally arrives as an online tool. Achieving a high score (ardamis.com is a 96/100) should be on every web developer’s list of things to do before the culmination of a project.

Enter a URL and Page Speed Online will run performance tests based on a set of best practices known to reduce page load times.

  • Optimizing caching – keeping your application’s data and logic off the network altogether
  • Minimizing round-trip times – reducing the number of serial request-response cycles
  • Minimizing request overhead – reducing upload size
  • Minimizing payload size – reducing the size of responses, downloads, and cached pages
  • Optimizing browser rendering – improving the browser’s layout of a page

WebPagetest

http://www.webpagetest.org/

WebPagetest is an excellent application for users who want the same sort of detailed reporting that one gets with Page Speed.

  • Load time speed test on first view (cold cache) and repeat view (hot cache), first byte and start render
  • Optimization checklist
  • Enable keep-alive, HTML compression, image compression, cache static content, combine JavaScript and CSS, and use of CDN
  • Waterfall
  • Response headers for each request

Load Impact

http://loadimpact.com/pageanalyzer.php

Load Impact is an online load testing service that lets you load- and stress test your website over the Internet. The page analyzer analyzes your web page performance by emulating how a web browser would load your page and all resources referenced in it. The page and its referenced resources are loaded and important performance metrics are measured and displayed in a load-bar diagram along with other per-resource attributes such as URL, size, compression ratio and HTTP status code.

ByteCheck

http://www.bytecheck.com/

ByteCheck is a super minimal site that return your page’s all-important time to first byte (TTFB). Time to first byte is the time it takes for a browser to start receiving information after it has started to make the request to the server, and is responsible for a visitor’s first impression that a page is fast- or slow-loading.

Web Page Analyzer

http://websiteoptimization.com/services/analyze/

My opinion is that the Web Page Analyzer report is good for beginners without much technical knowledge of things like gzip compression and Expires headers. It’s a bit dated, and is primarily concerned with basics like how many images a page contains. It tells you how fast you can expect your page to load for dial-up visitors, which strikes me as quaint and not particularly useful.

  • Total HTTP requests
  • Total size
  • Total size per object type (CSS, JavaScript, images, etc.)
  • Analysis of number of files and file size as compared to recommended limits

The Performance Grader

http://www.joomlaperformance.com/component/option,com_performance/Itemid,52/

This is another simplistic analysis of a site, like Web Page Analyzer, that returns its analysis in the form of pass/fail grades on about 14 different tests. I expect that it would be useful for developers who want to show a client a third-party’s analysis of their work, if the third-party is not terribly technically savvy.

One unique thing about this tool, though, is that it totals up the size of all images referenced in CSS files (even those that the current page isn’t using).

  • HTML Size
  • Total Size
  • Total Requests
  • Generation Time
  • Number of Hosts
  • Number of Images
  • Size of Images
  • Number of CSS Files
  • Size of CSS Files
  • Number of Script Files
  • Size of Script Files
  • HTML Encoding
  • Valid HTML
  • Frames