[Previous] [Table of Contents] [Next]

# Mapping Network Drives

Just as you can share printers, you can share drives or folders within a network. In Windows, you can map these network resources to local drives, which is useful if you use older software that doesn't support UNC network paths or if you prefer to use a drive such as D: or E: to access a device.

In this section, we'll look at a simple script that maps three shareable network resources to the X:, Y:, and Z: drives. The program then displays a list of all mapped drives in a dialog box (Figure 11-4).

Figure 11-4 Drive mapping

You can map a network resource (such as a drive or a folder) to a local drive by using the MapNetworkDrive method of the WshNetwork object. The method's first parameter is the name of the local drive (the drive letter and the colon). The second parameter specifies a network resource in UNC format.

Two other, optional, parameters specify the user name and the password to establish the mapping. If you use these two parameters, you run the risk that the password won't be secure. For more details on the syntax of the MapNetworkDrive method, see the Windows Script Host Reference.

> NOTE

> The MapNetworkDrive method causes a run-time error if the local drive is already mapped or if the UNC path to the network resource isn't valid.

The following VBScript sequence catches run-time errors while creating the mapping:

    Set WshNetwork = WScript.CreateObject("WScript.Network")
    On Error Resume Next
    WshNetwork.MapNetworkDrive "X:", \\ROM\C
    ErrCheck Err.Number

The first statement creates the WshNetwork object. On Error Resume Next forces the interpreter to continue with the next statement in the script. The third line uses the MapNetworkDrive method to map a network drive to a local drive. The ErrCheck procedure in the last line ensures that a run-time error is reported to the user in a customized dialog box (not a run-time error dialog box, which terminates the script).

To list all mapped local drives, this sample uses the EnumNetworkDrives method, which returns an object containing a collection with all mapped drives. The following statement creates the collection:

    Set oDrives = WshNetwork.EnumNetworkDrives

You can then use the following loop to process all items in the collection:

    For i = 0 To oDrives.Count - 1 Step 2
        If oDrives(i) <> " " Then
            Text = Text & oDrives(i) & "   " & oDrives(i+1) & vbCrLf
        End If
    Next

The first entry in the collection returns the local drive name, and the second entry contains the UNC path to the mapped network resource. Therefore, the loop uses a step width of 2.

The full VBScript implementation is shown in Listing 11-10.

Listing 11-10 MapDrives.vbs

    '*************************************************
    ' File:    MapDrives.vbs (WSH sample in VBScript)
    ' Author:  (c) G. Born
    '
    ' Mapping network drives and listing them in a
    ' dialog box
    '*************************************************
    Option Explicit

    Const machine = "\\Wien"

    Dim Text, Title, i
    Dim WshNetwork, oDrives         ' Object variable

    Text = "Drive mapping" & vbCrLf & vbCrLf
    Title = "WSH sample - by G. Born"

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

    ' Map some drives.
    On Error Resume Next
    WshNetwork.MapNetworkDrive "X:", machine & "\C"
    ErrCheck Err.Number

    WshNetwork.MapNetworkDrive "Y:", machine & "\D"
    ErrCheck Err.Number

    WshNetwork.MapNetworkDrive "Z:", machine & "\E"
    ErrCheck Err.Number

    ' Get collection from EnumNetworkDrives property.
    Set oDrives = WshNetwork.EnumNetworkDrives

    For i = 0 To oDrives.Count - 1 Step 2
        If oDrives(i) <> " " Then
            Text = Text & oDrives(i) & "   " & oDrives(i+1) & vbCrLf
        End If
    Next

    MsgBox Text, vbOKOnly + vbInformation, Title

    '###################
    ' Show error.
    Sub ErrCheck(nr)
        Select Case nr
            Case 0
                ' No error
            Case -2147024829
                WScript.Echo "Error: Network resource doesn't exist"
            Case -2147024811
                WScript.Echo "Error: Drive already mapped"
            Case Else
                WScript.Echo "Error: " & CStr(nr)
        End Select
    End Sub

    '*** End

## The JScript Implementation

To prevent run-time errors when using the MapNetworkDrive method on an already mapped drive, you can use the following statements:

    WshNetwork.RemoveNetworkDrive("X:");
    WshNetwork.MapNetworkDrive("X:", "\\\\ROM\\C");

The command removes the mapping of a drive and creates a new assignment. If a mapping doesn't exist, the RemoveNetworkDrive method raises a run-time error. To establish run-time error handling, you can move the RemoveNetworkDrive and MapNetworkDrive methods into separate procedures. These procedures use try...catch error handling to force script execution and show run-time errors. Listing 11-11 shows the full code listing.

Listing 11-11 MapDrives.js

    //************************************************
    // File:    MapDrives.js (WSH sample in JScript)
    // Author:  (c) G. Born
    //
    // Mapping network drives and listing them in a
    // dialog box
    //************************************************

    var machine = "\\\\Wien\\";

    // Create a new WshNetwork object, which we need
    // to access network properties.
    var WshNetwork = WScript.CreateObject("WScript.Network");

    // Remove mapping to prevent run-time errors.
    DisconnectDrive("X:");
    DisconnectDrive("Y:");
    DisconnectDrive("Z:");

    // Create some mappings for network drives.
    ConnectDrive("X:", machine + "C");
    ConnectDrive("Y:", machine + "D");
    ConnectDrive("Z:", machine + "E");

    // List all mapped drives.
    Text = "Mapped drives \n";

    var oDevices = WshNetwork.EnumNetworkDrives();

    for (var i = 0; i <= oDevices.length - 2; i = i + 2)
    {
        Text = Text + oDevices(i) + "    " + oDevices(i+1) + "\n";
    }

    WScript.Echo(Text);

    function DisconnectDrive(drive)
    {
        try
        {
            WshNetwork.RemoveNetworkDrive(drive);
        }
        catch (e)
        {
            if (e != 0)       // Display a possible error message.
                WScript.Echo("Remove " + drive, "\nError code : ",
                             e.number, e.description);
        }
    }

    function ConnectDrive(drive, resource)
    {
        try
        {
            WshNetwork.MapNetworkDrive(drive, resource);
        }
        catch (e)
        {
            if (e != 0)          // Display a possible error message.
                WScript.Echo("Map " + drive + " to " + resource,
                             "\nError code : ", e.number, e.description);
        }
    }

    //*** End

## Logon Scripts

You can execute WSH scripts in Windows during logon to customize the user environment (map network drives and printers, for example). In Windows 2000, an administrator can also set up scripts to be executed during startup, shutdown, logon, and logoff (using the Microsoft Management Console). I'll come back to this topic in Chapter 13.