Отправить заявку

Автоматизируем установку сетевых принтеров, дисков и ярлыков в Active Directory

Каждый раз, когда на работе появляется новый пользователь - системный администратор выполняет рутинную работу по настройке рабочего места для этого пользователя. А ведь практически все можно упростить до безобразия. Главное проявить инициативность и тогда появится много свободного времени :)На работе коллеги показали очень интересный скрипт на VBS, при запуске скрипта пользователю, в зависимости от того в какой группе он находится устанавливаются соответствующие ярлыки, принтеры и сетевые диски. И так нам понадобится сам скрипт на VBS и 3 csv файла: 1 — содержит принтеры, 2-й ярлыки, 3-й сетевые диски.

Скрипт:

'***********************************************************************************************************' 
' File:     RU-ALL-CONNECT-PRN.VBS 
' Script connects network printers if user is a member of specific group 
' Also creates shortcut on user's desktop 
' Code written : Nikolay Ermakov' 
' Date : 06 May 2005' 
' Release : 2' 
'***********************************************************************************************************'  
' Initialize vars 
' ********* Change this for testing **************** 
Const strDomain = "YOURDOMAIN.RU" 'Domain of the user 
Const UseNTServer = 0   'Sets whether this script runs when logging on locally 
                        'to Windows Servers. 
                        'Values are: 1 (Yes) OR 0 (No) 
 
Dim strPrnFilename : strPrnFilename = "Printerlist.csv"    'Printer cfg file name 
Dim strLnkFilename : strLnkFilename = "Linklist.csv"    'Shortcuts cfg file name 
Dim strDrvFilename : strDrvFilename = "Drivelist.csv"    'Drives cfg file name 
Dim objWshNetwork : Set objWshNetwork = CreateObject("Wscript.Network") 
Dim strLogonPath        'Path to location from where the script is running 
Dim strOSProdType       'OS Product type (WinNT, LanmanNT, ServerNT) 
Dim strWorkstation      'Local Computer Name 
Dim objWshShell 
Dim strUserID  
Dim GroupList 
Dim objIntExplorer 
Dim freeletter 
'Dim strTarget, strArguments , strDesktop 
' ************************************************************************************************************' 
 
On Error Resume Next 
 
Set fso = CreateObject("Scripting.FileSystemObject") 
Set ADSysInfo = CreateObject("ADSystemInfo") 
Set objWshShell = CreateObject( "WScript.Shell" ) 
 
strUserID = objWshNetwork.UserName 
strCompID = objWshNetwork.ComputerName & "$" 
 
'Gather some basic system info 
Call GetSystemInfo 
 
If IsTerminalServerSession = True Then ' Exit if the script is running in a terminal server sessionend if 
    'Wscript.Echo "Terminal session" 
    'Call CleanUp  
End if 
 
'Exit if we are logging on locally to a server and the script is set to NOT run on servers 
If UseNTServer = 0 AND (strOSProdType = "LanmanNT" OR strOSProdType = "ServerNT") AND Not (IsTerminalServerSession) Then  
    Call CleanUp 
End If   
 
 
'Setup IE for use as a status message window 
'Call SetupIE 
'Display welcome message 
'Call UserPrompt ("Welcome " & strUserID) 
'Add horizontal line as a 'break' 
'objIntExplorer.Document.WriteLn("<hr style=""width:100%""></hr>") 
 
strPrnFilename = strLogonPath & "\" & strPrnFilename 
strLnkFilename = strLogonPath & "\" & strLnkFilename 
strDrvFilename = strLogonPath & "\" & strDrvFilename 
 
'Check for error getting username 
If strUserID = "" Then 
  objWshShell.Popup "Logon script failed - Contact the Helpdesk @ x 1234", ,"Logon script", 48 
  End If 
 
If fso.FileExists(strDrvFilename) Then            'If DriveMapping cfg file exists 
    Set drvlist = Fso.OpenTextFile(strDrvFilename) 
    ' make File into an Array 
    aGroup = Split(drvlist.Readall,vbcrlf) 
    For x = 1 to UBound(aGroup) ' Read the entire CSV from the second line 
        driveline = aGroup(x) 
        Group = Left(driveline,InStr(driveline,",")-1) 'Extract group list 
        if ADSI_IsMemberOfGroup(strDomain, strUserID, Group) Then ' If you're in the group 
'            MsgBox "Member of the group " & Group 
            ' It is a member - Connect drive 
            driveline = Mid(driveline,InStr(driveline,",")+1) ' Remove the GroupName from the line 
            Drive = Left(driveline,InStr(driveline,",")-1) ' Extract Drive Letter 
            Path = Mid(driveline,InStr(driveline,",")+1) ' Extract the path 
            'Wscript.Echo "GroupName: " & vbTab & Group & vbCr _ 
            '& "----------------------------------" & vbCr _ 
            '& "Drive Letter: " & vbTab & Drive & vbCr _ 
            '& "Drive Path: " & vbTab & Path & vbCr _ 
            '& ""  
            on Error Resume Next 
            If drive = "*" then    'Connect to any free drive letter if drive letter configured as "*" 
                For freeletter = Asc("K") to Asc("Z")  
                    If Not fso.driveExists (chr(freeletter)) Then 
                        drive = (Chr(freeletter)) & ":"     
                        Exit For  
                    End If  
                Next  
            end if 
            If (fso.DriveExists(drive) <> True) and (Drive<>"!!") Then ' If The Drive is not already mapped 
                objWshNetwork.MapNetworkDrive drive,path ' Map The Drive 
                wscript.sleep 300 
            End If  
        End If 
    Next 
End If 
 
If fso.FileExists(strPrnFilename) Then            'If Printer cfg file exists 
    Set prnlist = Fso.OpenTextFile(strPrnFilename) 
    ' make File into an Array 
    aGroup = Split(prnlist.Readall,vbcrlf) 
    For x = 1 to UBound(aGroup) ' Read the entire CSV from the second line 
        printerline = aGroup(x) 
        Group = Left(printerline,InStr(printerline,",")-1) 'Extract group list 
        if ADSI_IsMemberOfGroup(strDomain, strUserID, Group) Then ' If you're in the group 
'            MsgBox "Member of the group " & Group 
            ' It is a member - Connect printer 
            Path = Mid(printerline,InStr(printerline,",")+1) ' Extract the path 
            on Error Resume Next 
            'Call UserPrompt ("Successfully added printer connection to: " & Path) 
            objWshNetwork.AddWindowsPrinterConnection Path 
            wscript.sleep 300 
        End If 
    Next 
End If 
 
If fso.FileExists(strLnkFilename) Then            'If Shortcut cfg file exists 
    Set lnklist = Fso.OpenTextFile(strLnkFilename) 
    ' make File into an Array 
    aGroup = Split(lnklist.Readall,vbcrlf) 
    strDesktop = objWshShell.SpecialFolders("Desktop") 
     
    For x = 1 to UBound(aGroup) ' Read the entire CSV from the second line 
        linkline = aGroup(x) 
        Group = Left(linkline,InStr(linkline,",")-1) 'Extract group list 
'        if ADSI_IsMemberOfGroup(strDomain, strUserID, Group) then MsgBox "User is Member of the group " & Group end if 
'        if ADSI_CompIsMemberOfGroup (strDomain, strCompID, Group) Then MsgBox "Comp is Member of the group " & Group end if 
        if ADSI_IsMemberOfGroup(strDomain, strUserID, Group) or ADSI_CompIsMemberOfGroup (strDomain, strCompID, Group) Then 
        ' If you're in the group 
        ' It is a member - Create shortcut 
            linkline = Mid(linkline,InStr(linkline,",")+1) ' Remove the GroupName from the line 
            LinkName = Left(linkline,InStr(linkline,",")-1) 'Extract shortcut name 
            linkline = Mid(linkline,InStr(linkline,",")+1) ' Remove the LinkName from the line 
            strTarget = Left(linkline,InStr(linkline,",")-1) 'Extract shortcut target (path to program) 
            linkline = Mid(linkline,InStr(linkline,",")+1) ' Remove the Target from the line 
            strArguments = Left(linkline,InStr(linkline,",")-1) 'Extract arguments 
            linkline = Mid(linkline,InStr(linkline,",")+1) ' Remove the arguments from the line 
            strWDir = Left(linkline,InStr(linkline,",")-1) ' Extract Working dir 
            linkline = Mid(linkline,InStr(linkline,",")+1) ' Remove Working dir from the line 
            strIconLoc = linkline ' Extract the Icon Location 
            on Error Resume Next 
            set oSLink = objWshShell.CreateShortcut(strDesktop & "\" & LinkName) 
            oSLink.TargetPath = strTarget     ' you can use UNC instead of driveletter as well 
            oSLink.Arguments = strArguments 
            oSLink.IconLocation = strIconLoc 
            oSLink.WorkingDirectory = strWDir 
            oSLink.Save                 ' create the shortcut 
        End If 
    Next 
End If 
 
 
'Inform user that logon process is done 
'Add horizontal line as a 'break' 
'objIntExplorer.Document.WriteLn("<hr style=""width:100%""></hr>") 
'Call UserPrompt ("Finished network logon processes") 
'Wait 10 seconds 
'Wscript.Sleep (10000) 
'Close Internet Explorer 
'objIntExplorer.Quit( ) 
Call CleanUp 'This is end of running script 
 
 
'ADSI_IsMemberOfGroup.asp -- last revision 2003-11-12 TGH 
'------------------------------------------------------------------------------- 
'Copyright (c) 2003, Thomas G. Harold and Beta Research Corp, All rights reserved. 
' 
'Redistribution and use in source and binary forms, with or without modification,  
'are permitted provided that the following conditions are met: 
' 
' * Redistributions of source code must retain the above copyright notice, this  
'   list of conditions and the following disclaimer. 
' * Redistributions in binary form must reproduce the above copyright notice, this  
'   list of conditions and the following disclaimer in the documentation and/or other  
'   materials provided with the distribution. 
' * Neither the name of Beta Research Corp nor the names of its contributors may be used  
'   to endorse or promote products derived from this software without specific prior  
'   written permission. 
' 
'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY  
'EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES  
'OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT  
'SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,  
'INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,  
'PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS  
'INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT  
'LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE  
'OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
'------------------------------------------------------------------------------- 
 
'ADSI_IsMemberOfGroup(sDomain,sUserName,sGroup) 
' 
'Returns TRUE if the user is a member of group X, also searches through nested groups 
'Failure mode results in FALSE being returned. 
'Assumption is that both the USERNAME and the GROUPNAME are in the same DOMAIN 
'Another assumption is that the domain that is passed in is also that of the current 
'Active Directory tree.  (Bad assumption, but I can't find code to map a NT style 
'domain name to the active directory equivalent.) 
' 
'sDomainName = "DOMAIN" (left side of the Request.ServerVariables("AUTH_USER") variable) 
'sUserName = "USERNAME" (right side of the Request.ServerVariables("AUTH_USER") variable) 
'sGroup = "GROUPNAME" name of the ADSI group that the user has to be a member of 
' 
'Example: If ADSI_IsMemberOfGroup("DOMAIN1", "Scott", "Domain Administrators") Then 
 
Private Function ADSI_IsMemberOfGroupRecurse( sRootDomain,  sParentDN, sUsername) 
    'Response.Write "ADSI_IsMemberOfGroupRecurse([" & sRootDomain & "], [" & sParentDN & "], [" & sUsername & "])<br>" & vbCrLf 
 
    Dim oConn, oCommand, bFound 
    bFound = False 
    Set oConn = CreateObject("ADODB.Connection") 
    Set oCommand = CreateObject("ADODB.Command")     
    oConn.Provider = "ADsDSOObject" 
    oConn.Open "Active Directory Provider" 
    Set oCommand.ActiveConnection = oConn 
     
    'Check for direct membership     
    oCommand.CommandText = "SELECT SAMAccountName, Name, DistinguishedName, ADSPath " & _ 
        "FROM 'LDAP://" & sRootDomain & "' " & _ 
        "WHERE memberOf='" & sParentDN & "' " & _ 
        "AND SAMAccountName='" & sUserName & "' " & _ 
        "AND objectClass='user' ORDER BY NAME" 
    Set rsLDAP = oCommand.Execute 
    If Not rsLDAP.EOF Then 
        'Response.Write "DIRECT MEMBER! Name=[<b>" & rsLDAP.Fields("Name") & "</b>] SAMAccountName=[<b>" & _ 
        '   rsLDAP.Fields("SAMAccountName") & "</b>] DistinguishedName=[<b>" & _ 
        '   rsLDAP.Fields("DistinguishedName") & "</b>] ADsPath=[" & _ 
        '   rsLDap.Fields("ADsPath") & "]<br>" & vbCrLf 
        bFound = True 
    End If 
     
    If Not bFound Then 
        'Otherwise get the list of groups within the current group and recurse into them 
        oCommand.CommandText = "SELECT SAMAccountName, Name, DistinguishedName, ADSPath " & _ 
            "FROM 'LDAP://" & sRootDomain & "' " & _ 
            "WHERE memberOf='" & sParentDN & "' AND objectClass='group' ORDER BY NAME" 
        Set rsLDAP = oCommand.Execute 
        While (Not rsLDAP.EOF) And (Not bFound) 
            'Response.Write "SUB-GROUP: Name=[<b>" & rsLDAP.Fields("Name") & "</b>] SAMAccountName=[<b>" & _ 
            '   rsLDAP.Fields("SAMAccountName") & "</b>] DistinguishedName=[<b>" & _ 
            '   rsLDAP.Fields("DistinguishedName") & "</b>] ADsPath=[" & _ 
            '   rsLDap.Fields("ADsPath") & "]<br>" & vbCrLf      
            bFound = ADSI_IsMemberOfGroupRecurse(sRootDomain, rsLDAP.Fields("DistinguishedName"), sUserName)             
            rsLDAP.MoveNext 
        Wend 
    End If 
 
    Set oCommand = Nothing 
    Set oConn = Nothing 
    ADSI_IsMemberOfGroupRecurse = bFound 
End Function 
 
Public Function ADSI_IsMemberOfGroup( sDomain, sUserName, sGroup ) 
    ADSI_IsMemberOfGroup = False     
    'Response.Write "ADSI_IsMemberOfGroup([" & sDomain & "], [" & sUserName & "], [" & sGroup & "])<br>" & vbCrLf 
 
    'NOTE: We're making the assumption that there is only ONE domain, and that it's 
    'the proper domain that happens to match the sDomain parameter. 
    Set oRoot = GetObject("LDAP://RootDSE") 
    sRootDomain = oRoot.Get("DefaultNamingContext") 
    'Response.Write "sRootDomain=[" & sRootDomain & "]<br>" & vbCrLf 
     
    Dim oConn, oCommand, oRoot, sRootDomain 
    Set oConn = CreateObject("ADODB.Connection") 
    Set oCommand = CreateObject("ADODB.Command")     
    oConn.Provider = "ADsDSOObject" 
    oConn.Open "Active Directory Provider" 
    Set oCommand.ActiveConnection = oConn 
         
    'Get the group's distinguished name information 
    Dim GroupDistinguishedName 
    oCommand.CommandText = "SELECT SAMAccountName, Name, DistinguishedName, ADSPath " & _ 
        "FROM 'LDAP://" & sRootDomain & "' " & _ 
        "WHERE SAMAccountName='" & sGroup & "' ORDER BY NAME" 
    Set rsLDAP = oCommand.Execute 
    If Not rsLDAP.EOF Then 
        'Response.Write "GROUP DISTINGUISHED NAME: Name=[<b>" & rsLDAP.Fields("Name") & "</b>] SAMAccountName=[<b>" & _ 
        '   rsLDAP.Fields("SAMAccountName") & "</b>] DistinguishedName=[<b>" & _ 
        '   rsLDAP.Fields("DistinguishedName") & "</b>] ADsPath=[" & _ 
        '   rsLDap.Fields("ADsPath") & "]<br>" & vbCrLf 
        GroupDistinguishedName = rsLDAP.Fields("DistinguishedName") 
    End If 
 
    ADSI_IsMemberOfGroup = ADSI_IsMemberOfGroupRecurse( sRootDomain, GroupDistinguishedName, sUsername) 
     
    Set oCommand = Nothing 
    Set oConn = Nothing 
    Set oRoot = Nothing 
End Function 
 
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
' 
' Sub:      SetupIE 
' 
' Purpose:  Set up Internet Explorer for use as a status message window 
' 
' Input: 
' 
' Output: 
' 
' Usage:    Call SetupIE 
' 
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
 
Private Sub SetupIE 
  On Error Resume Next 
  Dim strTitle    'Title of IE window 
  Dim intCount    'Counter used during AppActivate 
  strTitle = "Logon script status" 
  'Create reference to objIntExplorer 
  'This will be used for the user messages. Also set IE display attributes 
  Set objIntExplorer = Wscript.CreateObject("InternetExplorer.Application") 
  With objIntExplorer 
    .Navigate "about:blank" 
    .ToolBar   = 0 
    .Menubar   = 0 
    .StatusBar = 0 
    .Width     = 600 
    .Height    = 350 
    .Left      = 100 
    .Top       = 100 
  End With 
 
  'Set some formating 
 
  With objIntExplorer.Document 
    .WriteLn ("<!doctype html public>") 
    .WriteLn   ("<head>") 
    .WriteLn    ("<title>" & strTitle & "</title>") 
    .WriteLn     ("<style type=""text/css"">") 
    .WriteLn      ("body {text-align: left; font-family: Courier New; font-size: 8pt}") 
    .WriteLn     ("</style>") 
    .WriteLn   ("</head>") 
  End With 
  'Wait for IE to finish 
  Do While (objIntExplorer.Busy) 
    Wscript.Sleep 200 
  Loop 
  'Show IE 
  objIntExplorer.Visible = 1 
  'Make IE the active window 
  For intCount = 1 To 100 
    If objWshShell.AppActivate(strTitle) Then Exit For 
    WScript.Sleep 50 
  Next 
 
End Sub 
 
 
' Sub:      UserPrompt 
' 
' Purpose:  Use Internet Explorer as a status message window 
' 
' Input:    strPrompt 
' 
' Output:   Output is sent to the open Internet Explorer window 
' 
' Usage: 
' 
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
 
Private Sub UserPrompt( strPrompt ) 
  On Error Resume Next 
  objIntExplorer.Document.WriteLn (strPrompt & "<br />") 
End Sub 
 
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
' 
' Sub:      Cleanup 
' Purpose:  Release common objects and exit script 
' Input: 
' Output: 
' Usage:    Call Cleanup 
' 
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
Sub Cleanup 
  On Error Resume Next 
  Set objFileSys     = Nothing 
  Set objWshNetwork  = Nothing 
  Set objWshShell    = Nothing 
  Set objIntExplorer = Nothing 
  ' Exit script 
  WScript.Quit( ) 
End Sub 
 
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
' Sub:      GetSystemInfo 
' Purpose:  Gather basic information about the local system 
' Input: 
' Output:   strDomain, strOSProdType, strWorkstation, strLogonPath 
' Usage:    Call GetSystemInfo 
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
Private Sub GetSystemInfo 
  On Error Resume Next 
  'Get domain name 
  If objWshShell.ExpandEnvironmentStrings( "%OS%" ) = "Windows_NT" Then 
    strDomain = objWshNetwork.UserDomain 
  Else 
    strDomain = objWshShell.RegRead( "HKLM\System\CurrentControlSet\" & _ 
                "Services\MSNP32\NetWorkProvider\AuthenticatingAgent" ) 
  End If 
  'Get Product Type from Registry (WinNT, LanmanNT, ServerNT) 
  strOSProdType = objWshShell.RegRead( _ 
    "HKLM\System\CurrentControlSet\Control\ProductOptions\ProductType") 
  'Get computer name 
  If IsTerminalServerSession = True Then 
    'Set strWorkstation to the real name and not the name of the server 
    strWorkstation = objWshShell.ExpandEnvironmentStrings( "%CLIENTNAME%" ) 
  Else 
    strWorkstation = objWshNetwork.ComputerName 
  End If 
  'Get the path to the location from where the script is running 
  strLogonPath = Left( Wscript.ScriptFullName, _ 
    ( InstrRev( Wscript.ScriptFullName, "\") -1)) 
End Sub 
 
 
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
' Function: IsTerminalServer 
' Purpose:  Determine if the script is running in a terminal server session 
' Input: 
' Output: 
'           True if running in a terminal server session 
'           False if not running in a terminal server session 
' Usage: 
'           If IsTerminalServerSession = True Then <Do Something> 
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
Private Function IsTerminalServerSession 
  On Error Resume Next 
  Dim strName 
  'Detect if this is a terminal server session 
  'If it is, set some names to the terminal server client name 
  strName = objWshShell.ExpandEnvironmentStrings( "%CLIENTNAME%" ) 
  If strName <> "%CLIENTNAME%" AND strName <> "" Then  
    IsTerminalServerSession = True 
  Else 
    IsTerminalServerSession = False 
  End if 
End Function 
 
Private Function ADSI_CompIsMemberOfGroupRecurse( sRootDomain,  sParentDN, sCompName) 
    'Response.Write "ADSI_IsMemberOfGroupRecurse([" & sRootDomain & "], [" & sParentDN & "], [" & sUsername & "])<br>" & vbCrLf 
 
    Dim oConn, oCommand, bFound 
    bFound = False 
    Set oConn = CreateObject("ADODB.Connection") 
    Set oCommand = CreateObject("ADODB.Command")     
    oConn.Provider = "ADsDSOObject" 
    oConn.Open "Active Directory Provider" 
    Set oCommand.ActiveConnection = oConn 
     
    'Check for direct membership     
    oCommand.CommandText = "SELECT SAMAccountName, Name, DistinguishedName, ADSPath " & _ 
        "FROM 'LDAP://" & sRootDomain & "' " & _ 
        "WHERE memberOf='" & sParentDN & "' " & _ 
        "AND SAMAccountName='" & sCompName & "' " & _ 
        "AND objectClass='computer' ORDER BY NAME" 
    Set rsLDAP = oCommand.Execute 
    If Not rsLDAP.EOF Then 
        'Response.Write "DIRECT MEMBER! Name=[<b>" & rsLDAP.Fields("Name") & "</b>] SAMAccountName=[<b>" & _ 
        '   rsLDAP.Fields("SAMAccountName") & "</b>] DistinguishedName=[<b>" & _ 
        '   rsLDAP.Fields("DistinguishedName") & "</b>] ADsPath=[" & _ 
        '   rsLDap.Fields("ADsPath") & "]<br>" & vbCrLf 
        bFound = True 
    End If 
     
    If Not bFound Then 
        'Otherwise get the list of groups within the current group and recurse into them 
        oCommand.CommandText = "SELECT SAMAccountName, Name, DistinguishedName, ADSPath " & _ 
            "FROM 'LDAP://" & sRootDomain & "' " & _ 
            "WHERE memberOf='" & sParentDN & "' AND objectClass='group' ORDER BY NAME" 
        Set rsLDAP = oCommand.Execute 
        While (Not rsLDAP.EOF) And (Not bFound) 
            'Response.Write "SUB-GROUP: Name=[<b>" & rsLDAP.Fields("Name") & "</b>] SAMAccountName=[<b>" & _ 
            '   rsLDAP.Fields("SAMAccountName") & "</b>] DistinguishedName=[<b>" & _ 
            '   rsLDAP.Fields("DistinguishedName") & "</b>] ADsPath=[" & _ 
            '   rsLDap.Fields("ADsPath") & "]<br>" & vbCrLf      
            bFound = ADSI_CompIsMemberOfGroupRecurse(sRootDomain, rsLDAP.Fields("DistinguishedName"), sCompName)             
            rsLDAP.MoveNext 
        Wend 
    End If 
 
    Set oCommand = Nothing 
    Set oConn = Nothing 
    ADSI_CompIsMemberOfGroupRecurse = bFound 
End Function 
 
Public Function ADSI_CompIsMemberOfGroup( sDomain, sCompName, sGroup ) 
    ADSI_CompIsMemberOfGroup = False     
    'Response.Write "ADSI_IsMemberOfGroup([" & sDomain & "], [" & sUserName & "], [" & sGroup & "])<br>" & vbCrLf 
 
    'NOTE: We're making the assumption that there is only ONE domain, and that it's 
    'the proper domain that happens to match the sDomain parameter. 
    Set oRoot = GetObject("LDAP://RootDSE") 
    sRootDomain = oRoot.Get("DefaultNamingContext") 
    'Response.Write "sRootDomain=[" & sRootDomain & "]<br>" & vbCrLf 
     
    Dim oConn, oCommand, oRoot, sRootDomain 
    Set oConn = CreateObject("ADODB.Connection") 
    Set oCommand = CreateObject("ADODB.Command")     
    oConn.Provider = "ADsDSOObject" 
    oConn.Open "Active Directory Provider" 
    Set oCommand.ActiveConnection = oConn 
         
    'Get the group's distinguished name information 
    Dim GroupDistinguishedName 
    oCommand.CommandText = "SELECT SAMAccountName, Name, DistinguishedName, ADSPath " & _ 
        "FROM 'LDAP://" & sRootDomain & "' " & _ 
        "WHERE SAMAccountName='" & sGroup & "' ORDER BY NAME" 
    Set rsLDAP = oCommand.Execute 
    If Not rsLDAP.EOF Then 
        'Response.Write "GROUP DISTINGUISHED NAME: Name=[<b>" & rsLDAP.Fields("Name") & "</b>] SAMAccountName=[<b>" & _ 
        '   rsLDAP.Fields("SAMAccountName") & "</b>] DistinguishedName=[<b>" & _ 
        '   rsLDAP.Fields("DistinguishedName") & "</b>] ADsPath=[" & _ 
        '   rsLDap.Fields("ADsPath") & "]<br>" & vbCrLf 
        GroupDistinguishedName = rsLDAP.Fields("DistinguishedName") 
    End If 
 
    ADSI_CompIsMemberOfGroup = ADSI_CompIsMemberOfGroupRecurse( sRootDomain, GroupDistinguishedName, sCompName) 
     
    Set oCommand = Nothing 
    Set oConn = Nothing 
    Set oRoot = Nothing 
End Function 

Дальше в этой же директории создаем Printerlist.csv, он должен быть вида

GroupName, PrinterPath
grp-printer1,\\PrinterServer1\Printer1
grp-printer2,\\PrinterServer2\Printer2

Где grp-printer1 — это группа AD, в которой пользователи, которым в свою очередь нужно подключить этот принтер. \\PrinterServer1\Printer1 — это путь до принтера с общим доступом. Одной группе можно назначить сколько угодно принтеров и принтер может соответствовать нескольким группам.

Еще нам понадобится LnkList.csv

Group name, Shortcut name, Target, Arguments, WorkingDir, IconLocation
LNK-group,LnkName.lnk,\\Server\ShareName\FileName,,\\Server\ShareName\,\\Server\ShareName\IcoName,0

Где LNK-group — группа AD, в которой пользователи, \\Server\ShareName\FileName — путь к нужному файлу или директории, если это директория то в начале нужно написать explorer.exe, мы запускаем без аргументов, поэтому две запятые, \\Server\ShareName\ — рабочая папка для ярлыка, \\Server\ShareName\IcoName — путь к иконке, обычно совпадает с именем файла.

И последний файл — drivelist.csv

GroupName, DriveLetter, DrivePath
drive-group,X:,\\FileServer\Share

Где drive-group — группа AD, в которой пользователи, X: — буква, которой обозначаем подключаемый сетевой диск, \\FileServer\Share — пусть к папке с общим доступом.

Вот собственно и все, нужно только создать соответствующие группы, добавить туда пользователей и в групповой политике в сценариях входа пользователя добавить выполнение скрипта.

Другие публикации