As a network administrator, we often use vbscripts to map network shares. Our end users are constantly wanting new shares with specific drive letters in many different locations. So as administrators, it is our job to script a drive mapping solution for those users.
In this article, I'm going to talk about drive mapping for end users. First, we have to specify a drive letter (i.e. T: ) when mapping. This is typically supplied by the user(s) requesting the drive mapping. Next we need the server and share (i.e. \\myserver\sharename). Finally, we write the code to map the share to that drive letter and pop it into their script. We also use other logic to determine who maps what drive, but we'll save those techniques for another article.
First, let's look at the basics of drive mapping. In order to map drives, we use the Wscript.Network object. From here, we can access all kinds of things like enumerating all the current network drive mappings, disconnecting drives, and mapping drives. There are several other methods available using the link above.
Now that we have our object, we can disconnect drives using the RemoveNetworkDrive method and we can map drives using the MapNetworkDrive method:
Easy huh? But what if a user already has a different share mapped to drive X:?
As administrators, we have the power to force users to map certain shares to certain drive mappings. Often times, we enforce this by disconnecting anything on the requested drive mapping before we map it. This ensures we have the correct mapping on the drive letter. This seems like overkill in my opinion. Why waste time disconnecting and reconnecting a drive if we don't need to?
To get around this, we can use the EnumNetworkDrives method. This returns an array of drive letters and server shares. We can then iterate through the list and compare to see if they exist. Let's add this capability and create a nice function we can reuse:
Looks long huh? In summary, the function enumerates all the network drive mappings first. Then it looks through the list for the requested drive letter to see if it's in use. If so, it checks the share mapping on that drive letter. If it's not correct, it disconnects and connects it proper. If the drive letter is not in use, it then maps the share to the requested drive letter.
And because it is a function that returns True or False, we can use the results as well:
There you have it. A better drive mapping solution. It's not perfect by no means, but it's better than just disconnecting wildly. I plan on adding more logic to search for shares mapped on other letters to ensure we don't get double mappings and to migrate people to the correct ones in times were we need to change the drive letter (and they will, end users are fickle).
Till next time!
Have a burning VBScript question to be answered? Send it in and you may just be featured in our next article... and get your question answered. :)