Add Computer to AD Group Script

I got this script from Microsoft that adds a computer as a member to a security group in Active Directory. As we want to automate everything, this script can be very useful during deployment. A typical scenario can be to enable the computer for Direct Access or wireless network.

Click the title to read the full post

Instructions for use with Microsoft Deployment Toolkit / SCCM

  1. Copy the script into your deploymentshare\scripts
  2. In task sequence, add “run command line”
  3. In the command line, add Cscript.exe %SCRIPTROOT%\AddGroup.vbs  Group1 Group2 Group3
  4. Run it with an account that has the neccesary permissions to add members to the ad group

addgroup1

addgroup2

Add Computer to AD Group Script

Script: AddGroup.wsf

Const ADS_PROPERTY_APPEND = 3
Set WshShell = WScript.CreateObject("WScript.Shell")
'----Get Computer DN------

Set objADSysInfo = CreateObject("ADSystemInfo")
ComputerDN = objADSysInfo.ComputerName
strcomputerdn = "LDAP://" & computerDN
Set objADSysInfo = Nothing

'----Connect AD-----

Set oRoot = GetObject("LDAP://rootDSE")
strDomainPath = oRoot.Get("defaultNamingContext")
Set oConnection = CreateObject("ADODB.Connection")
oConnection.Provider = "ADsDSOObject"
oConnection.Open "Active Directory Provider"

Count = WScript.Arguments.Count
For i = 0 To  count-1  	
	Group = WScript.Arguments(i)
	Addgroup Group
Next 

'----Get Group DN------
Function Addgroup(groupname)
	Set oRs = oConnection.Execute("SELECT adspath FROM 'LDAP://" & strDomainPath & "'" & "WHERE objectCategory='group' AND " & "Name='" & GroupName & "'")
	If Not oRs.EOF Then
		strAdsPath = oRs("adspath")
	End If
	If IsEmpty(strAdsPath) = False  Then 
		Const ADS_SECURE_AUTHENTICATION = 1
		Set objGroup = GetObject(stradspath) 
		Set objComputer = GetObject(strComputerDN)
		If (objGroup.IsMember(objComputer.AdsPath) = False) Then
			objGroup.PutEx ADS_PROPERTY_APPEND, "member", Array(computerdn)
			objGroup.SetInfo
		End If
	End If 
End Function

Anders Rødland

Anders Rødland started his IT career in 2006. My main focus is MS Configuration Manager and client management, and I currently hold active 15 Microsoft certifications. Certified on Windows Server, Windows Client, SQL, Exchange and System Center Configuration Manager. Anders Rødland also holds an ITIL Foundation certification. This is my private blog and do not represent my employer. I use this to share information that I find useful. Sharing is caring.