Link GPO to OU (Perl)

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 Perl code from this site.

# This Perl code links a GPO to an OU in the specified domain

# ---------------------------------------------------------------
# Adapted from VBScript code contained in 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 ------
my $strDomainDN = "<DomainDN>";   # e.g. dc=rallencorp,dc=com
my $strGPO      = "<GPOName>";    # e.g. WorkstationsGPO
my $strOUDN     = "<OrgUnitDN>";  # e.g. ou=Workstations,dc=rallencorp,dc=com
# ------ END CONFIGURATION ---------
use Win32::OLE;
$Win32::OLE::Warn = 3;
my $strBaseDN  =  "<LDAP://cn=policies,cn=system,$strDomainDN>;";
my $strFilter  = "(&(objectcategory=grouppolicycontainer)" .
                 "(objectclass=grouppolicycontainer)" .
                 "(displayname=$strGPO));";
my $strAttrs   = "ADsPath;";
my $strScope   = "OneLevel";

my $objConn = Win32::OLE->CreateObject("ADODB.Connection");
$objConn->{Provider} = "ADsDSOObject";
$objConn->Open;
my $objRS = $objConn->Execute($strBaseDN . $strFilter . $strAttrs . $strScope);
if (not $objRS->EOF) {
   $objRS->MoveFirst;
}

if ($objRS->RecordCount == 1) {
   $strGPOADsPath = $objRS->Fields(0)->Value;
   print "GPO Found: $strGPOADsPath\n";
}
elsif ($objRS->RecordCount == 0) {
   print "Did not founding matching GPO for: $strGPO\n";
   exit;
}
elsif ($objRS->RecordCount > 1) {
   print "More than 1 GPO found matching: $strGPO\n";
   exit;
}

my $objOU = Win32::OLE->GetObject("LDAP://" . $strOUDN);

my $strGPLink = $objOU->Get("gpLink");
if (Win32::OLE->LastError &&
     not( Win32::OLE->LastError =~ /0x8000500d/)) {
     print "Fatal error while (retreiving gpLink attribute: ",Win32::OLE->LastError;
     exit;
} 

$objOU->Put("gpLink", $strGPLink . "[" . $strGPOADsPath . ";0]");
$objOU->SetInfo;
print "GPO successfully linked\n"

This code has been viewed 1406 times.

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