Script to connect & disconnect mapped drive


Recommended Posts

  sam_goffe said:

net use [DRIVE]: \\[PATH]\

net use [DRIVE]: \\[PATH]\ /DELETE

just put them in a batch file.

thanks... this is a start. however, since users tend to forget, I want it to remove after they are done with the directory. I figured the best way would be when they log off. can this be done?

Can't see the need to disconnect at log off.

' ########################################################################
'  Written in VBScript.
'  Establishes map drives.
'  Assign to OU Group Policy under USER CONFIG, WINDOWS SETTINGS, SCRIPTS, LOGON SCRIPT.
'
'  This script will: 
'  (1) check if the drive is already connected and, if so, disconnect it.
'  (2) map the drive.
'
'  Arguments are as follows: 
'	 MAPIT  DRIVE-LETTER as string,  PATH as string, USER as string, PASSWORD as string
'	 (1) Do not specify colon in drive letter.
'	 (2) Do not end path with a forward slash.
'	 (3) If user and password are not required to establish map, then specify a zero-length string as follows:  ""
'
' Reference Microsoft info at:
' http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/wsmthmapnetworkdrive.asp
' ########################################################################

' Create the Shell or environment for the commands:
Set WshShell = WScript.CreateObject("WScript.Shell")
' Define objects:
Set WshNetwork = WScript.CreateObject("WScript.Network")
Set oDrives = WshNetwork.EnumNetworkDrives()

' ====================================
' DEFINE WHO TO CONTACT for pop-up messages:
' ====================================
strContactMessage = "If you require assistance, please contact IT Support."

' ==================
' DEFINE DRIVES TO MAP:
' ==================
Mapit "m", "\\server1\share1", "", ""
Mapit "n", "\\server1\share2", "", ""

' ========
' CLEAN UP:
' ========
Set WshShell = Nothing
Set WshNetwork = Nothing
Set oDrives = Nothing

' ##################################
' DO NOT MODIFY ANYTHING BELOW THIS POINT...
'   unless you are familiar with the proper settings.
' ##################################
Sub Mapit(strLetter, strPath, strUser, strPass)

	' Define the DriveLetter:
	DriveLetter = strLetter & ":"

	' Define the remote path:
	RemotePath = strPath

	' Pop-up Notices (set to False to disable notices, otherwise set to True):
	bPopReminder = True

	' Define known errors to trap:
	Dim arrErrCode(1)
	Dim arrErrDesc(1)
	arrErrCode(0) = -2147023694
	arrErrCode(1) = -2147024811
	arrErrDesc(0) = "Unable to map drive " & DriveLetter & " to " & RemotePath _
		& " due to a previously defined remembered map with the same letter." _
		& vbCrLf & vbCrLf & "Please MANUALLY disconnect map drive " & DriveLetter _
		& ", then Log Out and Log back in."
	arrErrDesc(1) = "Unable to map drive " & DriveLetter & " to " & RemotePath _
		& " since " & DriveLetter & ": was previously reserved by your computer." _
		& vbCrLf & vbCrLf & "(Refer to Management, Shared Folders, Shares)"

	' Define whether the map information should be removed from the current user's profile:
	bForceRemoveFromProfile = True
	bRemoveFromProfile = True

	' Define whether the map information should be stored in the current user's profile:
	bStoreInProfile = False

	' Check if already connected:
	AlreadyConnected = False
	For i = 0 To oDrives.Count - 1 Step 2
		If LCase(oDrives.Item(i)) = LCase(DriveLetter) Then AlreadyConnected = True
	Next

	' Attempt to map the drive.  If already mapped, first attempt disconnect:
	If AlreadyConnected = True then
		WshNetwork.RemoveNetworkDrive DriveLetter, bForceRemoveFromProfile, bRemoveFromProfile
		If Not strUser = "" Then
			WshNetwork.MapNetworkDrive DriveLetter, RemotePath, bStoreInProfile, strUser, strPass
		Else
			WshNetwork.MapNetworkDrive DriveLetter, RemotePath, bStoreInProfile
		End If
'		If bPopReminder Then WshShell.PopUp "Drive " & DriveLetter & " disconnected, then connected successfully to " & RemotePath
	Else
		On Error Resume Next
		If Not strUser = "" Then
			WshNetwork.MapNetworkDrive DriveLetter, RemotePath, bStoreInProfile, strUser, strPass 
		Else
			WshNetwork.MapNetworkDrive DriveLetter, RemotePath, bStoreInProfile
		End If
		If Err.Number <> 0 Then
			bKnownError = False
			For I = LBound(arrErrCode) To UBound(arrErrCode)
				If Err.Number = arrErrCode(I) Then
					bKnownError = True
					strPopMessage = arrErrDesc(I)
					' Display the Disconnect Network Drives window:
					If Err.Number = arrErrCode(0) Then
						Set objWSH = Wscript.CreateObject("WScript.Shell")
						objWSH.Run "rundll32.exe shell32.dll,SHHelpShortcuts_RunDLL Disconnect", 1, true
					End If
					Exit For
				End If
			Next
			If Not bKnownError Then
				strPopMessage = "Unable to map drive " & DriveLetter & " to " & RemotePath _
					& " due to reason stated below."
			End If
			' Display warning message:
			strPopMessage = "WARNING!!   WARNING!!   WARNING!!   WARNING!!" _
				& vbCrLf & vbCrLf & strPopMessage _
				& vbCrLf & vbCrLf & Err.Description & " (error " & Err.Number & ")" _
				& vbCrLf & vbCrLf & strContactMessage
			WshShell.PopUp strPopMessage
		Else
'			If bPopReminder Then WshShell.PopUp "Drive " & DriveLetter & " connected successfully to " & RemotePath
		End If
	End If

' ====================================
' Rename those mapped drive.
' Why have "Share1 on server1" when you can have "Share 1"
' ====================================

mDrive = "M:\"
Set oShell = CreateObject("Shell.Application")
oShell.NameSpace(mDrive).Self.Name = "Share 1"

mDrive = "N:\"
Set oShell = CreateObject("Shell.Application")
oShell.NameSpace(mDrive).Self.Name = "Share 2"

	' Release resources:
	Set objWSH = Nothing

	' Slight pause to ensure each pass has time to commit:
	wscript.sleep 200
End Sub

  Quote
' ====================================

' Rename those mapped drive.

' Why have "Share1 on server1" when you can have "Share 1"

' ====================================

mDrive = "M:\"

Set oShell = CreateObject("Shell.Application")

oShell.NameSpace(mDrive).Self.Name = "Share 1"

mDrive = "N:\"

Set oShell = CreateObject("Shell.Application")

oShell.NameSpace(mDrive).Self.Name = "Share 2"

' Release resources:

Set objWSH = Nothing

' Slight pause to ensure each pass has time to commit:

wscript.sleep 200

End Sub

Didn't know that was possible. Nice tip, thanks.

instead of specifying a drive letter you can use the symbol * instead, this means the mapped drive will use the next available drive letter..

usefull if some users have usb pens etc plugged in that are taking up the drive letter specified in the script

(although thats less likely if you specify something like Z: )

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Here are all the new features Microsoft added to Teams in June 2025 by Usama Jawad Microsoft Teams is one of the most used software when it comes to online communication and collaboration, especially in enterprise environments. Even though there are still many features that people want in Teams, Microsoft tries to appease as many as it can with regular updates to the tool. Now, the Redmond tech firm has published a roundup of all the capabilities it added to Teams during the month of June 2025. Starting off with chat and collaboration improvements, we have an enhanced spellchecker offering support in up to three languages, with users being given the ability to add corrections to their personal dictionary too. In addition, the new chat and channels experience is now rolling out to Government Community Cloud (GCC) customers. Next, we have improvements to the meetings, webinars, and town halls experience. Loop-powered meeting notes are now available for GCC-High and Department of Defense (DoD) customers, and non-Teams users have the ability to join town hall meetings through Cloud Video Interoperability (CVI) join codes. It is also possible for those invited to join town halls and and webinars using sign-in details, such as PSTN. In a similar vein, town hall organizers can select individuals to manage the screen that is being shown to attendees. Organizers have more control over the broadcast of notifications too, and can also pull in a participant into the call directly and have them present their screen seamlessly. Lastly, town hall usage reports are now available in Teams Admin Center for additional insights. For those more interested on the hardware side of things, the following devices are now Teams-certified: Yealink MeetingBoard Pro MTRA Series-65, 75, and 86 inch Logitech 4K Pro Webcam (for consumer) Logitech Brio Ultra HD Pro Business Webcam (for business) Yealink RoomPanel E2 (8-inch) and E2 Plus (10 inch) Logitech Rally Board 65 + Tap IP for Teams Rooms on Android (wireless) Crestron Videobar 70 EPOS ADAPT 660 USB-C PolyStudio V12 Logitech Zone 305 (with native Bluetooth) That's not all, though. There are several other enhancements present across frontline worker solutions, security, and Teams Phone and Rooms. Read about them in detail here.
    • not if the other person can see the nickname you are setting ?
    • Sure, buddy, sure... let's compare the contents of the article to the stupid thumbnail, it's clearly the same thing and it has the same importance, of course.
    • ha..... man we must buy the wrong stuff because every one we've had has had a crease visible at work
    • I mean my expectations right now are near zero so how much lower?
  • Recent Achievements

    • Week One Done
      dennis Nebeker earned a badge
      Week One Done
    • One Year In
      timothytoots earned a badge
      One Year In
    • One Month Later
      CHUNWEI earned a badge
      One Month Later
    • Week One Done
      TIGOSS earned a badge
      Week One Done
    • First Post
      henryj earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      466
    2. 2
      +FloatingFatMan
      194
    3. 3
      ATLien_0
      163
    4. 4
      Xenon
      78
    5. 5
      Som
      73
  • Tell a friend

    Love Neowin? Tell a friend!