Tuesday 13 March 2018

map drive script

This VBscript will map a drive using a subroutine. The script can be modified to map multiple drives using the subroutine. Can be useful as a login script. Tested on Windows 2000 through to Windows 10.


'==========================================================================
'MapDrive.vbs
'Created by Timothy Bourne
'http://www.imric.co.uk
'Last Modified: 11th November 2009
'==========================================================================
'This VBscript will map a drive using a subroutine. The script can be 
'modified to map multiple drives using the subroutine. Can be useful as a 
'login script.
'==========================================================================

Option Explicit
On Error Resume Next

Dim objNetwork, objPassword, objCheckDrive
Dim strLocalName, strRemoteName, strUser
Dim bUpdateProfile, bAlreadyConnected
Dim i

Set objNetwork = Wscript.CreateObject("WScript.Network")

'Create drive mapping for Z: (this section can be copied for multiple drives)
strLocalName = "Z:"
strRemoteName = "\\Server01\data"
strUser = objNetwork.UserName 'Will use the current logged in username.
bUpdateProfile = FALSE 'Drive mapping will not be perminant.
EnumDrives 'Runs the subroutine to connect drive Z:

WScript.Quit

'EnumDrives subroutine
Sub EnumDrives

bAlreadyConnected = FALSE
Set objCheckDrive = objNetwork.EnumNetworkDrives()

'Check if the drive is already connected or not.
For i = 0 To objCheckDrive.Count - 1 Step 2
If objCheckDrive.Item(i) = strLocalName Then bAlreadyConnected = True
Next 

If bAlreadyConnected = True then
    WScript.Echo VbCrLf & strLocalName & " drive is already connected. Disconnecting it..."
'If the drive letter already exists, disconnect it...
    objNetwork.RemoveNetworkDrive strLocalName 
'... then connect it to the specified path.
    objNetwork.MapNetworkDrive strLocalName, strRemoteName, bUpdateProfile, strUser
    WScript.Echo strLocalName & " drive was reconnected to successfully."
Else
'If the drive letter dosn't exist, connect it to the specified path.
    objNetwork.MapNetworkDrive strLocalName, strRemoteName, bUpdateProfile, strUser
    WScript.Echo strLocalName & " drive was connected successfully."
End If
End Sub

No comments:

Post a Comment