[Previous] [Table of Contents] [Next]

Retrieving the User, Domain, or Computer Name

Windows allows you to retrieve the user name, domain name, or computer name from property pages of your Network Neighborhood property sheet. You can also use properties of the WshNetwork object to retrieve these names. You can create the object as a WScript subobject:

Set WshNetwork = WScript.CreateObject("WScript.Network")

You then access the properties of the object by using this WshNetwork object variable. The properties are as follows:

UserDomain is valid only if the machine is connected to a domain-oriented network such as Microsoft Windows NT Server or Microsoft Windows 2000 Server. If a Windows 95 or Windows 98 workstation is connected to a workgroup network, WSH returns an empty string (Figure 11-1, right). On a Windows 2000 machine, the property contains the name of the workstation, not the name of the workgroup (Figure 11-1, left).

Click to view at full size.

Figure 11-1 Network properties (Windows 2000, left; Windows 98, right)

The VBScript program shown in Listing 11-1 retrieves these properties and shows them in a dialog box. (Like the other samples shown in this chapter, Network.vbs is in the \WSHDevGuide\Chapter11 folder on the book's companion CD.)

Listing 11-1 Network.vbs

' File:    Network.vbs (WSH sample in VBScript) 
' Author:  (c) G. Born
' Showing the user name, domain name, and 
' workgroup name
Option Explicit 

Dim Text, Title
Dim WshNetwork         ' Object variable

Text = "Networking information" & vbCrLf & vbCrLf
Title = "WSH sample - by G. Born"

' Create a new WshNetwork object to access network properties.
Set WshNetwork = WScript.CreateObject("WScript.Network")

Text = Text & "Computer name : " & WshNetwork.ComputerName & vbCrLf
Text = Text & "Domain : " & WshNetwork.UserDomain & vbCrLf
Text = Text & "User name : " & WshNetwork.UserName & vbCrLf

MsgBox Text, vbOKOnly + vbInformation, Title

'*** End

The JScript Implementation

The JScript version, Network.js, is shown in Listing 11-2.

Listing 11-2 Network.js

// File:    Network.js (WSH sample in JScript) 
// Author:  (c) G. Born
// Showing the user name, domain name, and 
// workgroup name

var Text = "Networking information\n\n";

// Create WshNetwork object to access network properties.
var WshNetwork = WScript.CreateObject("WScript.Network");

Text = Text + "Computer name : " + WshNetwork.ComputerName + "\n";
Text = Text + "Domain : " + WshNetwork.UserDomain + "\n";
Text = Text + "User name : " + WshNetwork.UserName + "\n";


//*** End