Wednesday, November 4, 2009

Login scripts

While we're on the subject of VBS scripting, I have written some login scripts that can map drives and printers based on group membership, username, OU, etc. so you no longer need to have different scripts for different groups/OUs in Active Directory:

On Error Resume Next
Set oWSH = CreateObject("WScript.Shell")
Set oNet = CreateObject("WScript.Network")
Set oFS = CreateObject("Scripting.FileSystemObject")

sUsername = LCase(oNet.Username)
sComputerName = oWSH.ExpandEnvironmentStrings("%COMPUTERNAME%")
sMyDocs = "\\fileserver\users\" & sUsername & "\My Documents\"

Set oRootDSE = GetObject("LDAP://rootDSE")
Set oConnection = CreateObject("ADODB.Connection")
oConnection.Open "Provider=ADsDSOObject;"
Set oCommand = CreateObject("ADODB.Command")
oCommand.ActiveConnection = oConnection
oCommand.CommandText = " ">;(&(objectCategory=User)(samAccountName=" & sUsername & "));distinguishedName;subtree"
Set oRecordSet = oCommand.Execute
sDistinguishedName = oRecordSet.Fields("DistinguishedName")

Set oUser = GetObject("LDAP://" & sDistinguishedName)
oGroups = oUser.GetEx("memberOf")
bFinance = False
bAP = False
bSD = False
For Each g In oGroups
If InStr(g, "Finance")> 0 Then bFinance = True
If InStr(g, "Accounts Payable")> 0 Then bAP = True
If InStr(g, "San Diego")> 0 Then bSD = True

'Map drive for everyone
oNet.MapNetworkDrive "S:", "\\fileserver\shared"

'Map drive by group
If bFinance Then
oNet.MapNetworkDrive "P:", "\\fileserver\finance"
End If

'Map printers by group
If bAP Then
oNet.AddWindowsPrinterConnection "\\printserver\HP4100_AP"
oNet.AddWindowsPrinterConnection "\\printserver\Canon3380"
End If

'Map printer by location and computername prefix
If bSD And Left(sComputerName, 3) = "VDI" Then
oNet.AddWindowsPrinterConnection "\\printserver\HP6300_SD"
End If

'Map drive for one user on one workstation
If sUsername = "jsmith" And sComputerName = "VDI-XP-013" Then
oNet.MapNetworkDrive "P:", "\\fileserver\marketing"
End If

'Map drive for administrator
If sUsername = "administrator" Then
oNet.RemoveNetworkDrive "T:"
oNet.MapNetworkDrive "T:", "\\fileserver\install"
End If

'Make sure My Documents was created under home dir
If Not oFS.FolderExists(sMyDocs) then
End If

'Map printer for single user
If sUsername = "sjones" Then
oNet.AddWindowsPrinterConnection "\\sjones\hp_p1006"
End If

Function FindMapped(sLetter, sShare)
bFound = False
Set oDrives = oNet.EnumNetworkDrives
For i = 0 to oDrives.Count - 1 Step 2
If LCase(oDrives.Item(i)) = LCase(sLetter) Then
bFound = (LCase(oDrives.Item(i+1)) = LCase(sShare))
End If
FindMapped = bFound
End Function

No comments:

Post a Comment