Link GPO to OU (VBScript)

This code can be found in Chapter 5 of Active Directory Cookbook, 2nd edition

Purchase XP Cookbook or Networking Recipes for only $25 plus shipping! While supplies last.

Find out how to download all of the VBScript code from this site.

' This VBScript code links a GPO to an OU in the specified domain

' ---------------------------------------------------------------
' From the book "Active Directory Cookbook" by Robbie Allen
' Publisher: O'Reilly and Associates
' ISBN: 0-596-00466-4
' Book web site: http://rallenhome.com/books/adcookbook/code.html
' ---------------------------------------------------------------

' ------ SCRIPT CONFIGURATION ------
strDomainDN = "<DomainDN>"   ' e.g. dc=rallencorp,dc=com
strGPO      = "<GPOName>"    ' e.g. WorkstationsGPO
strOUDN     = "<OrgUnitDN>"  ' e.g. ou=Workstations,dc=rallencorp,dc=com
' ------ END CONFIGURATION ---------

strBaseDN  =  "<LDAP://cn=policies,cn=system,dc=" & strDomainDN & ">;"
strFilter  = "(&(objectcategory=grouppolicycontainer)" & _
               "(objectclass=grouppolicycontainer)" & _
               "(displayname=" & strGPO & "));"
strAttrs   = "ADsPath;"
strScope   = "OneLevel"

set objConn = CreateObject("ADODB.Connection")
objConn.Provider = "ADsDSOObject"
objConn.Open "Active Directory Provider"
set objRS = objConn.Execute(strBaseDN & strFilter & strAttrs & strScope)
if objRS.EOF <> TRUE then
   objRS.MoveFirst
end if

if objRS.RecordCount = 1 then
   strGPOADsPath = objRS.Fields(0).Value
   WScript.Echo "GPO Found: " & strGPOADsPath
elseif objRS.RecordCount = 0 then
   WScript.Echo "Did not founding matching GPO for: " & strGPO
   Wscript.Quit
elseif objRS.RecordCount > 1 then
   WScript.Echo "More than 1 GPO found matching: " & strGPO
   Wscript.Quit
end if

set objOU = GetObject("LDAP://" & strOUDN)

on error resume next
strGPLink = objOU.Get("gpLink")
if Err.Number then
   if Err.Number <> -2147463155 then  
      WScript.Echo "Fatal error while retreiving gpLink attribute: " & _
                    Err.Description
      Wscript.Quit
   end if
end if 
on error goto 0

objOU.Put "gpLink", strGPLink & "[" & strGPOADsPath & ";0]"
objOU.SetInfo
WScript.Echo "GPO successfully linked"

This code has been viewed 3010 times.

New from the creators of TechTasks.com: StatSheet.com