Listing11_Create_OU (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: $@";

# Need to get the Domain Naming Context value
my $rootdse = $ldap->search(base   => '',
                            filter => '(objectclass=*)',
                            scope  => 'base',
                            attrs => ['defaultNamingContext']);
die "Could not get RootDSE: ",$rootdse->error if $rootdse->code;
my $base_dn = ($rootdse->entries)[0]->get_value('defaultNamingContext');

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

my $ouObj = Net::LDAP::Entry->new();
$ouObj->dn("OU=Employees,$base_dn");
$ouObj->add(description => 'OU for XYZ Employee user accounts',
            objectclass => 'organizationalUnit');
my $result = $ouObj->update($ldap);
if ($result->code) {
   print "Error occurred when creating OU: ",$result->error,"\n";
}
else {
   print "OU Created\n";
}

This code has been viewed 659 times.

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