The Tao of Jace

January 7, 2009

JScript to Map Network Drive

Filed under: Archive — site admin @ 5:32 pm

So, more JScripting… This time I need to map a network drive for a program I’m moving between servers. Currently we’ve got people using a batch file or manually mapping the drive, but on the new server we’ll be applying a script that will handle this through group policy. I figure there’s a need for me to eventually map more than one drive and to also make sure there’s not anything already mapped to another location on the same drive. So I wrote a reusable script that checks through all the user’s mapped drives to see if the one we want is already taken and asks the user if it should reclaim the drive.

// MAP-DRIVE.js - Map Network Drive using provided specifications
// Author - Jace Gregg
// Version 1.0 - 07 January 2009
// -----------------------------------------------------------------'

// Just edit these fields:
//
var cTITLE = "Drive Mapping Script";
var mapDrive = "Z:";
var mapLocation = "\\\\path\\to\\server";
//
// No need to edit past here...

try {
	var shouldMap = null;
	var WshNetwork = WScript.CreateObject("WScript.Network");
	var oDrives = WshNetwork.EnumNetworkDrives();

	for(var i = 0; i < oDrives.length; i += 2) {
		if(oDrives.Item(i)==mapDrive) {
			if(oDrives.Item(i + 1).toLowerCase() != mapLocation) {
				// Drive is mapped to another location.  Ask the user if we should map to this location.
				shouldMap = msgbox("Drive " + mapDrive + " is mapped to \"" + oDrives.Item(i + 1).toLowerCase() + "\" but needs to be 

mapped to \"" + mapLocation + "\".  Do you want to automatically correct this?", null, null, 4 + 32);
			}
			else {
				shouldMap = false;
			}
		}
	}

	if(shouldMap == null) {
		shouldMap = true;
	}

	if(shouldMap) {
		WshNetwork.MapNetworkDrive(mapDrive, mapLocation);
	}
}
catch(e) {
	msgbox("Error " +  e.number + "\n\n" + e.description + "\nCould not connect network drive for this application.", null, null, 16);
}

function msgbox(message, title, popupTime, nType) {
	if(title == null) {
		title = cTITLE;
	}
	if(popupTime == null) {
		popupTime = 10;
	}
	var objWSH = WScript.CreateObject("Wscript.Shell");
	return objWSH.Popup(message, popupTime, title, nType);
}

You could add the ParseEnvironmentStrings method from my previous post and map to user directories or other various locations. Sure it’s not as efficient as it could be, but it does the trick. Feel free to change it to make it more efficient and use it however you want.

No Comments »

No comments yet.

RSS feed for comments on this post.

Leave a comment

You must be logged in to post a comment.

Powered by WordPress