The easiest way I know is to use the MapNetworkDrive method from
Windows Script Host:

  http://msdn.microsoft.com/library/en-us/script56/html/wsmthmapnetworkdrive.asp

Below is a sample Perl script which invokes this method.  (I have sent
this here before, but it is short so what the heck.)  You invoke it as
"map-drive.pl x: \\server\share" to map a drive.  The difference
between this and "net use" is that it forcibly unmaps the drive first.

Speaking of "net use", you could probably just use that.  But this is
cooler :-).

If you replace the last line with something like this:

  $wsh_network->MapNetworkDrive ($drive, $share, 0, 'user', 'password');

...it should do what you want.

 - Pat

use warnings;
use strict;

use Win32::OLE;

sub die_usage () {
    die "Usage: $0 <drive> <share>\n";
}

scalar @ARGV == 2
    or die_usage ();

my ($drive, $share) = @ARGV;

$drive =~ /^[a-z]:$/i
    or die_usage ();

# Bomb out completely if COM engine encounters any trouble.
Win32::OLE->Option ('Warn' => 3);

# Get WshNetwork object.  See
# <http://msdn.microsoft.com/library/en-us/script56/html/wsobjwshnetwork.asp>
my $wsh_network = Win32::OLE->CreateObject ('WScript.Network');

# Remove network drive forcibly, if it is already mapped. See
# <http://msdn.microsoft.com/library/en-us/script56/html/wsmthremovenetworkdrive.asp>
-e "$drive/"
    and $wsh_network->RemoveNetworkDrive ($drive, 1);

# Map network drive.  See
# <http://msdn.microsoft.com/library/en-us/script56/html/wsmthmapnetworkdrive.asp>
$wsh_network->MapNetworkDrive ($drive, $share);

Reply via email to