Monday, May 17, 2021

Powershell and Visual Basic logon scripts to map drives

On Error Resume Next 
' Ref: https://community.spiceworks.com/topic/1945685-gpo-drive-mapping-not-mapped-on-login-but-mapped-on-gpupdate
Set objSysInfo = CreateObject("ADSystemInfo")
strUserDN = objSysInfo.UserName
Set objUser = GetObject("LDAP://" & strUserDN)
Set objNetwork = CreateObject("Wscript.Network")
Set objShell = CreateObject("WScript.Shell")
Set FSO = CreateObject("Scripting.FileSystemObject")

'Map network share by group
arrGroups = objUser.GetEx("memberOf")
   For Each strGroup in arrGroups
        Set objGroup = GetObject("LDAP://" & strGroup)
        strGroupName = objGroup.CN

        Select Case strGroupName
 
        Case "N_share"
            objNetwork.MapNetworkDrive "Z:", "\\server\Network_share"

        'Case "Teachers"
            'objNetwork.MapNetworkDrive "K:", "\\fileserver\teachers$"

        End Select
Next



'Label the Network drives
Set WshNet = WScript.CreateObject("WScript.Network")
 Set oShell = CreateObject("Shell.Application")
 
Set nDrives = WshNet.EnumNetworkDrives
 
For i = 0 To nDrives.Count - 1 step 2
 path = nDrives.Item(i+1)
 drive = ndrives.Item(i)
 if drive <> "" then
 folders = Split(path,"\")
 foldername = folders(ubound(folders))
 oShell.NameSpace(drive & "\").Self.Name = foldername
 end if
 next
 
Set WshNet = Nothing
 Set oDrives = Nothing
 Set oShell = Nothing

And here's an example using VB (Visual Basic)
UnconnDrives
ConnectDrive "J:","\\fileserver\share-name1","Friendly share name 1"
ConnectDrive "K:","\\fileserver\share-name2","Friendly share name 2"
ConnectDrive "L:","\\fileserver\share-name3","Friendly share name 3"

'///////////////////
'// Connect a drive
Function ConnectDrive(Drive,Path,Description)
On Error Resume Next
Dim objNetwork,oScriptShell
Set objNetwork=WScript.CreateObject("WScript.Network")
Set oScriptShell=CreateObject("WScript.Shell")
Set oShell=CreateObject("Shell.Application")
err.clear
objNetwork.MapNetworkDrive Drive,Path
If Err.Number<>0 Then
oScriptShell.Popup "Connecting drive " & Drive & " (" & Path & ")" & VbCrLf & "Description=" & Err.Description & VbCrLf & "Code=" & Err.Number,5,"Error",16
Else
oShell.NameSpace(Drive).Self.Name=Description
End If
End Function

'////////////////////////////////
'// Unconnect all network drives
function UnconnDrives()
On Error Resume Next
Dim objNetwork
Dim i,colDrives
Set objNetwork=WScript.CreateObject("WScript.Network")
'Unmap existing drives
Set colDrives=objNetwork.EnumNetworkDrives
If colDrives.Count<>0 Then
For i=0 To colDrives.Count-1 Step 2
objNetwork.RemoveNetworkDrive colDrives(i),"True","True"
Next
End If
End function

No comments:

Post a Comment

DiskGenius and Hasleo Backup

DiskGenius is an all-in-one utility for disk partition management, OS migration and file recovery. https://www.diskgenius.com/ Hasleo offers...