' AddToGroup1.vbs ' VBScript program to add users in a text file to a group. ' ' ---------------------------------------------------------------------- ' Copyright (c) 2002-2010 Richard L. Mueller ' Hilltop Lab web site - http://www.rlmueller.net ' Version 1.0 - November 10, 2002 ' Version 1.1 - February 19, 2003 - Standardize Hungarian notation. ' Version 1.2 - January 25, 2004 - Modify error trapping. ' Version 1.3 - November 6, 2010 - No need to set objects to Nothing. ' This program reads user NT names from a text file and adds the users ' to a group. The name of the text file and the group sAMAccountName are ' passed to the program as parameters. The program uses the WinNT ' provider to bind to the group and user objects. The NetBIOS domain ' name is hardcoded. ' ' You have a royalty-free right to use, modify, reproduce, and ' distribute this script file in any way you find useful, provided that ' you agree that the copyright owner above has no warranty, obligations, ' or liability for such use. Option Explicit Dim objFile, objGroup, objFSO, strFile, strGroup Dim strNTName, objUser, strNetBIOSDomain, intCount Const ForReading = 1 ' NetBIOS domain name. strNetBIOSDomain = "MyDomain" ' Check for required arguments. If (Wscript.Arguments.Count < 2) Then Wscript.Echo "Required Argument Missing" & vbCrLf _ & "Syntax: cscript AddToGroup.vbs UserList.txt GroupName" Wscript.Quit(0) End If strFile = Wscript.Arguments(0) strGroup = Wscript.Arguments(1) ' Open the text file of user names. Set objFSO = CreateObject("Scripting.FileSystemObject") On Error Resume Next Set objFile = objFSO.OpenTextFile(strFile, ForReading) If (Err.Number <> 0) Then On Error GoTo 0 Wscript.Echo "Unable to open file " & strFile Wscript.Quit(1) End If ' Bind to the group object in Active Directory, using the WinNT ' provider. On Error Resume Next Set objGroup = GetObject("WinNT://" & strNetBIOSDomain & "/" _ & strGroup & ",group") If (Err.Number <> 0) Then On Error GoTo 0 Wscript.Echo "Unable to bind to group " & vbCrLf & strGroup objFile.Close Wscript.Quit(1) End If On Error GoTo 0 ' Read names from the text file, bind to the users, and add them to the ' group. intCount is the number of users added to the group. intCount = 0 Do Until objFile.AtEndOfStream strNTName = Trim(objFile.ReadLine) If (strNTName <> "") Then On Error Resume Next Set objUser = GetObject("WinNT://" & strNetBIOSDomain & "/" _ & strNTName & ",user") If (Err.Number <> 0) Then On Error GoTo 0 Wscript.Echo "User " & strNTName & " not found" Else objGroup.Add(objUser.AdsPath) If (Err.Number <> 0) Then On Error GoTo 0 Wscript.Echo "Error adding user " & strNTName & " to group " _ & strGroup Else On Error GoTo 0 intCount = intCount + 1 End If End If End If Loop Wscript.Echo CStr(intCount) & " members added to group " & strGroup ' Clean up. objFile.Close