Listing07_Enable_GC (Perl)

This code can be found in Chapter 7 of Managing Enterprise Active Directory Services

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.

# From the book "Managing Enterprise Active Directory Services"
# ISBN: 0-672-32125-4

use strict;
use Net::LDAP;

my $server  = 'dc1';
my $user    = 'administrator@xyz.com';
my $passwd  = 'password';

my $ldap = Net::LDAP->new($server)
           or die "Could not connect to $server: $@";

# Get configuration naming context
my $rootdse = $ldap->search(base   => '',
                            filter => '(objectclass=*)',
                            scope  => 'base',
                            attrs => ['configurationNamingContext']);
die "Could not get RootDSE: ",$rootdse->error if $rootdse->code;
my $config_dn =($rootdse->entries)[0]->get_value('configurationNamingContext');

my $bind = $ldap->bind($user, password => $passwd);
die "Could not bind to server: ", $bind->error if $bind->code;

# Find the server object for this DC
my $result = $ldap->search(base   => "cn=Sites,$config_dn",
                           scope  => 'subtree',
                           attrs  => [ 'distinguishedName' ],
                           filter => "(&(objectclass=server)
                                        (objectcategory=server)
                                        (cn=$server)) ");
die "Search returned an error: ", $result->error if $result->code;

my $numObjs = scalar $result->entries;
if ($numObjs == 1) {
   my $server_dn = ($result->entries)[0]->get_value('distinguishedName');
   $result = $ldap->search(base   => "cn=NTDS Settings,$server_dn",
                           scope  => 'onelevel',
                           attrs  => [ 'cn' ],
                           filter => "(&(objectclass=ntdsdsa)
                                        (objectcategory=ntdsdsa))");
   die "Search returned an error: ", $result->error if $result->code;
   my $ntdsObj = ($result->entries)[0];
   $ntdsObj->replace( options => 1);
   $result = $ntdsObj->update( $ldap );
   if ($result->code) {
      print "Error occurred when setting options attribute: ",$result->error;
   }
   else {
      print "Enabled GC for server $server\n";
   }
}
else {
   print "Search did not return expected results: ";
   print "$numObjs matching entries found\n";
}

This code has been viewed 739 times.

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