Link to home
Create AccountLog in
Avatar of timnjohnson
timnjohnsonFlag for United States of America

asked on

VbScript to map network drives, install multiples printers based on GroupMembership

Hi,  I would like to use Rob's vbscript below to do the following things:

1. map multiple network drives,
2. install multiple network printers based on GroupMembership
3.  And Set up Default printers for each group.  
AD enviro...........>
Rob's script below is a good start.     Any ideas that can put me into the right path....I'm just getting my hands on vbscripts and i'm putting every effort to there  

 ' First we get the current screen resolution so we can place
' our progress window in the centre
' See: http://www.microsoft.com/technet/scriptcenter/resources/qanda/jul05/hey0721.mspx
 
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
 
Set colItems = objWMIService.ExecQuery _
      ("Select PelsWidth,PelsHeight From Win32_DisplayConfiguration")
 
For Each objItem in colItems
      intScreenWidth = objItem.PelsWidth
      intScreenHeight = objItem.PelsHeight
Next
 
' Now create our display window and position it in the centre
intWidth = 320
intHeight = 240
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Navigate "about:blank"
objIE.Toolbar = 0
objIE.StatusBar = 0
objIE.AddressBar = 0
objIE.MenuBar = 0
objIE.Resizable = 0
While objIE.ReadyState <> 4
      WScript.Sleep 100
Wend
objIE.Left = (intScreenWidth / 2) - (intWidth / 2)
objIE.Top = (intScreenHeight / 2) - (intHeight / 2)
objIE.Visible = True
 
' Now run your normal code and you can use
' objIE.document.WriteLn "This is my message"
' anywhere in the code to update progress
 
objIE.Document.WriteLn "Running logon scripts. Please wait..." & "<BR>"
 
On Error Resume Next
 
Set objPrinters = CreateObject("WScript.Network")
Set objShell = CreateObject("WScript.Shell")
 
'Remove old printers
objIE.Document.WriteLn "Removing old printer objects..." & "<BR>"
objPrinters.RemovePrinterConnection "\\server\RW-470WP"
objPrinters.RemovePrinterConnection "\\server\RW-480WP"
 
'Install new Printers
objIE.Document.WriteLn "Mapping new printers..." & "<BR>"
objPrinters.AddWindowsPrinterConnection "\\server\Xerox2HPGL2"
objPrinters.AddWindowsPrinterConnection "\\server\Xerox2PS"
 
'Synchronizes the time with Server
objIE.Document.WriteLn "Synchronising your clock..." & "<BR>"
objShell.Run "cmd /c NET TIME \\server2 /set /y", 0, True
 
'Clean Up Memory Used
Set objShell = Nothing
Set objPrinters = Nothing
objIE.Document.WriteLn "<BR>" & "Finished running scripts. This window will close in three seconds."
WScript.Sleep 3000
objIE.Quit
Set objIE = Nothing
 
wscript.quit
 
Avatar of maze-uk
maze-uk

the Microsoft Technet Script Center Repository is your friend :-)
http://www.microsoft.com/technet/scriptcenter/scripts/default.mspx?mfr=true
Here is a snippet I created to map shares based on primary group that should lead you in the right direction.

Changing the mapping of drives to mapping network printers

and to set the default use

Set objPrinter = CreateObject("WScript.Network")
objPrinter.SetDefaultPrinter "\\ServerName\PrinterName"


if you need help merging the scripts let me know.


zf
LOL forgot the code,  this also checks the pc for the next avaiable drive letter to map too

zf
objNetwork.MapNetworkDrive strPrimaryGroupDrive, "\\SERVERNAME\PrimaryGroupShare", True
 
'Keeping what you have
'Map the PrimaryGroup drive outside the Select Case
'Then check each group in the select case and ignore the primary mapping the rest
'when attempting to map the rest call the routine to get the next available drive letter to map To
 
For Each Group In UserObj.groups
Dim strNextAvailableDrive
        If UCase(Group.Name) <> UCase(strPrimaryGroup) Then 'If not primary run select Case
         strNextAvailableDrive = GetNextDriveLetter()
                Select Case UCASE(Group.Name)
        
                        Case "ACC"
                                objNetwork.MapNetworkDrive strNextAvailableDrive, "\\SERVERNAME\Acc", True
                         
                        Case "ADM"
                                objNetwork.MapNetworkDrive strNextAvailableDrive, "\\SERVERNAME\ADM", True
                         
                        Case "CUS"
                                objNetwork.MapNetworkDrive strNextAvailableDrive, "\\SERVERNAME\CUS", True
                         
                        Case "ENG"
                                objNetwork.MapNetworkDrive strNextAvailableDrive, "\\SERVERNAME\Eng", True
                         
                        Case "EXP"
                                objNetwork.MapNetworkDrive strNextAvailableDrive, "\\SERVERNAME\EXP", True
                         
                        Case "FAC"
                                objNetwork.MapNetworkDrive strNextAvailableDrive, "\\SERVERNAME\FAC", True
                         
                        Case "HUM"
                                objNetwork.MapNetworkDrive strNextAvailableDrive, "\\SERVERNAME\HUM", True
                         
                        Case "MKT"
                                objNetwork.MapNetworkDrive strNextAvailableDrive, "\\SERVERNAME\MKT", True
                         
                        Case "MNT"
                                objNetwork.MapNetworkDrive strNextAvailableDrive, "\\SERVERNAME\MNT", True
                         
                        Case "SYS"
                                objNetwork.MapNetworkDrive strNextAvailableDrive, "\\SERVERNAME\Sys", True
                End Select
        
        End if 
 
Next
 
Private Function GetNextDriveLetter()
Set objDictionary = CreateObject("Scripting.Dictionary")
        strComputer = "."
        Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
        Set colDisks = objWMIService.ExecQuery("Select * from Win32_LogicalDisk")
                For Each objDisk in colDisks
                    objDictionary.Add objDisk.DeviceID, objDisk.DeviceID
                Next
                For i = 68 To 90 'Drives start at D: go thru to Z:
                        If i <> 83 Then ''Skip drive S: so we dont loose our primary group map
                            strDrive = Chr(i) & ":"
                                If objDictionary.Exists(strDrive) Then
                                Else
                                GetNextDriveLetter = strDrive
                                End If
                        End if
                Next
End function

Open in new window

that first script is to map shares based on secondary group membership and this one is to get the primary group id and translate that into the actual group name.

zf
Option Explicit
Dim strDomain,strUserName
strDomain = "NetBiosDomain"
strUserName = "UserName"
WScript.Echo ResolvePrimaryGroup(strDomain,StrUserName)
 
 
Private Function ResolvePrimaryGroup(strNTDomain, strUser)
Dim objUser, objConn, objComm, objRS, objGroup
Dim strFilter, strAttrs, strBase, strScope, strPrimaryGroup
 
 
 
Set objUser = GetObject("WinNT://" & strNTDomain & "/" & strUser & ",user")
strFilter = ""
For Each objGroup In objUser.Groups
   strFilter = strFilter & "(samAccountName=" & objGroup.Name & ")"
Next
strFilter = "(|" & strFilter & ")"
 
strBase = "<LDAP://" & strNTDomain & ">;"
strFilter = "(&(objectcategory=group)" & strFilter & ");"
strAttrs = "name,primaryGroupToken,cn;"
strScope = "subtree;"
Set objConn = CreateObject("ADODB.Connection")
objConn.Provider = "ADsDSOObject"
objConn.Open "Active Directory Provider"
Set objComm = CreateObject("ADODB.Command")
Set objComm.ActiveConnection = objConn
objComm.CommandText = strBase & strFilter & strAttrs & strScope
objComm.Properties("Page Size") = 1000
Set objRS = objComm.Execute
strPrimaryGroup = ""
While ((Not objRS.EOF) And (strPrimaryGroup = ""))
  If (objUser.PrimaryGroupID = objRS.Fields("primaryGroupToken").Value) Then
     strPrimaryGroup = objRS.Fields("name").Value
  End If
  objRS.moveNext
Wend
objConn.Close
ResolvePrimaryGroup = strPrimaryGroup
End Function

Open in new window

Mapping multiple printers


from
http://www.computerperformance.co.uk/Logon/LogonScript_Printer_Multiple.htm



zf
Option Explicit
Dim objNetwork, strLocal, strUNCPrinter1, strUNCPrinter2
strUNCPrinter1 = "\\grand\HPLaserJ"
strUNCPrinter2 = "\\zara\Epson"
Set objNetwork = CreateObject("WScript.Network")
objNetwork.AddWindowsPrinterConnection strUNCPrinter1
objNetwork.AddWindowsPrinterConnection strUNCPrinter2
 
WScript.Quit

Open in new window

Avatar of timnjohnson

ASKER


zoofan:
Thanks for all your time and effort:
The script you posted looks great but I haven't tested it yet.  This is the script I've been working on.
As I said my main objective is to:

1.  Map network drives based on Group membership
2. Map multiple printers and set default printers again based group membership.
3. A Welcome greeting msg box based on user's first name.

This is what MarkD sent me>>> I got errors when I tried to run the script but I know I messed up somewhere.



'==========================================================================
'
' NAME: LogonScript.vbs
'
' AUTHOR:  Mark D. MacLachlan, The Spider's Parlor
' URL   : http://www.thespidersparlor.com
' DATE  : 4/10/2003
'
' COMMENT: Enumerates current users' group memberships in given domain.
'
'==========================================================================


ON ERROR RESUME NEXT

Dim WSHShell, WSHNetwork, objDomain, DomainString, UserString, UserObj, Path


Set WSHShell = CreateObject("WScript.Shell")
Set WSHNetwork = CreateObject("WScript.Network")
Set objDomain = getObject("LDAP://rootDse")
DomainString = objDomain.Get("dnsHostName")

UserString = WSHNetwork.UserName
'Bind to the user object to get user name and check for group memberships later
Set UserObj = GetObject("WinNT://" & DomainString & "/" & UserString)

'Synchronizes the time with Server our NTP Server
WSHShell.Run "NET TIME \\dcimcf01 /set /y"

'Disconnect any drive mappings as needed.
WSHNetwork.RemoveNetworkDrive "F:"

'Disconnect ALL mapped drives
Set clDrives = WshNetwork.EnumNetworkDrives
For i = 0 to clDrives.Count -1 Step 2
    WSHNetwork.RemoveNetworkDrive clDrives.Item(i)
Next

'Give the PC time to do the disconnect, wait 300 milliseconds
wscript.sleep 300

'Now check for group memberships and map appropriate drives
For Each GroupObj In UserObj.Groups
    Select Case GroupObj.Name
'Check for group memberships and take needed action
        Case "ADMIN"
              WSHNetwork.MapNetworkDrive "r:", "\\mcf01\SCAN",True
            WSHNetwork.MapNetworkDrive "m:", "\\mcf01\cristest",True
            WSHNetwork.MapNetworkDrive "p:", "\\mcf01\common",True
            WSHNetwork.MapNetworkDrive "u:", "\\mcf01\PUBLIC",True
              WSHNetwork.AddWindowsPrinterConnection "\\mcf01\Hp ljet4050"
              WSHNetwork.SetDefaultPrinter "\\mcf01\Hp ljet4050"
              WSHNetwork.AddWindowsPrinterConnection "\\mcf01\XEROX_3035"
             
'Now check for group memberships and map appropriate drives
 For Each GroupObj In UserObj.Groups
    Select Case GroupObj.Name
    'Check for group memberships and take needed action
        Case "ACCOUNTING"
              WSHNetwork.MapNetworkDrive "U:", "\\mcf01\PUBLIC",True
            WSHNetwork.MapNetworkDrive "m:", "\\mcf01\cristest",True
            WSHNetwork.MapNetworkDrive "p:", "\\mcf01\common",True
              WSHNetwork.AddWindowsPrinterConnection "\\mcf01\Hp ljet3035"
              WSHNetwork.SetDefaultPrinter "\\mcf01\Hp ljet3035"
              WSHNetwork.AddWindowsPrinterConnection "\\mcf01\XEROX_3035"
             
End Select

Dim HourNow, Greeting
HourNow = Hour(Now)
If HourNow >5 And  HourNow <12 Then
       Greeting = "Good Morning "
Elseif HourNow =>12 And HourNow <16 Then
       Greeting = "Good Afternoon "
Else
       Greeting = "Good Evening "
End If



Next                                

'Clean Up Memory We Used
set UserObj = Nothing
set GroupObj = Nothing
set WSHNetwork = Nothing
set DomainString = Nothing
set WSHSHell = Nothing
Set WSHPrinters = Nothing
 

'Quit the Script
wscript.quit
Ok I foudnd one thing that would keep it from working you had two case selects but only one end select, combined them into one as that is all you really need.

Changed the select case objtgroup.name to all upper case to match what you used for group names in the case's.


also removed
'Disconnect any drive mappings as needed.
WSHNetwork.RemoveNetworkDrive "F:"

as the loop should disconnect them all


*NOTE* added a comment
DomainString = objDomain.Get("dnsHostName") '<-----And this should be the NETBIOS domain name not dnshostname open dos shell type set{enter} look at 'USERDOMAIN'




Try those changes out and let me know, thats all I found at the moment.



zf




'==========================================================================
'
' NAME: LogonScript.vbs
'
' AUTHOR:  Mark D. MacLachlan, The Spider's Parlor
' URL   : http://www.thespidersparlor.com
' DATE  : 4/10/2003
'
' COMMENT: Enumerates current users' group memberships in given domain.
'
'==========================================================================
 
 
ON ERROR RESUME NEXT
 
Dim WSHShell, WSHNetwork, objDomain, DomainString, UserString, UserObj, Path
 
 
Set WSHShell = CreateObject("WScript.Shell")
Set WSHNetwork = CreateObject("WScript.Network")
Set objDomain = getObject("LDAP://rootDse")
DomainString = objDomain.Get("dnsHostName") '<-----And this should be the NETBIOS domain name not dnshostname open dos shell type set{enter} look at 'USERDOMAIN'
 
UserString = WSHNetwork.UserName
'Bind to the user object to get user name and check for group memberships later
Set UserObj = GetObject("WinNT://" & DomainString & "/" & UserString)
 
'Synchronizes the time with Server our NTP Server
WSHShell.Run "NET TIME \\dcimcf01 /set /y"
 
'Disconnect ALL mapped drives
Set clDrives = WshNetwork.EnumNetworkDrives
For i = 0 to clDrives.Count -1 Step 2
    WSHNetwork.RemoveNetworkDrive clDrives.Item(i)
Next
 
'Give the PC time to do the disconnect, wait 300 milliseconds
wscript.sleep 300
 
'Now check for group memberships and map appropriate drives
For Each GroupObj In UserObj.Groups
    Select Case Lcase(GroupObj.Name)
'Check for group memberships and take needed action
        Case "ADMIN"
              WSHNetwork.MapNetworkDrive "r:", "\\mcf01\SCAN",True
              WSHNetwork.MapNetworkDrive "m:", "\\mcf01\cristest",True
              WSHNetwork.MapNetworkDrive "p:", "\\mcf01\common",True
              WSHNetwork.MapNetworkDrive "u:", "\\mcf01\PUBLIC",True
              WSHNetwork.AddWindowsPrinterConnection "\\mcf01\Hp ljet4050"
              WSHNetwork.SetDefaultPrinter "\\mcf01\Hp ljet4050"
              WSHNetwork.AddWindowsPrinterConnection "\\mcf01\XEROX_3035"
        Case "ACCOUNTING"
              WSHNetwork.MapNetworkDrive "U:", "\\mcf01\PUBLIC",True
              WSHNetwork.MapNetworkDrive "m:", "\\mcf01\cristest",True
              WSHNetwork.MapNetworkDrive "p:", "\\mcf01\common",True
              WSHNetwork.AddWindowsPrinterConnection "\\mcf01\Hp ljet3035"
              WSHNetwork.SetDefaultPrinter "\\mcf01\Hp ljet3035"
              WSHNetwork.AddWindowsPrinterConnection "\\mcf01\XEROX_3035"
             
	End Select
Next
 
	Dim HourNow, Greeting
	HourNow = Hour(Now)
	If HourNow >5 And  HourNow <12 Then
	       Greeting = "Good Morning "
	Elseif HourNow =>12 And HourNow <16 Then
	       Greeting = "Good Afternoon "
	Else
	       Greeting = "Good Evening "
	End If                       
 
'Clean Up Memory We Used
set UserObj = Nothing
set GroupObj = Nothing
set WSHNetwork = Nothing
set DomainString = Nothing
set WSHSHell = Nothing
Set WSHPrinters = Nothing
 
 
'Quit the Script
wscript.quit

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of zoofan
zoofan
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer