# This Perl code finds inactive computer accounts
# ---------------------------------------------------------------
# From the book "Active Directory Cookbook" by Robbie Allen
# ISBN: 0-596-00466-4
# ---------------------------------------------------------------
#-----------------------
# Script Configuration
#-----------------------
# Domain and container/OU to check for inactive computer accounts
my $domain = 'amer.rallencorp.com';
# set to empty string to query entire domain
my $computer_cont = 'cn=Computers,';
# Number of weeks used to find inactive computers
my $weeks_ago = 30;
#-----------------------
# End Configuration
#-----------------------
use strict;
use Win32::OLE;
$Win32::OLE::Warn = 3;
$Win32::OLE::Warn = 3;
use Math::BigInt;
# Must convert the number of seconds since $weeks_ago
# to a large integer for comparison against lastLogonTimestamp
my $sixmonth_secs = time - 60*60*24*7*$weeks_ago;
my $intObj = Math::BigInt->new($sixmonth_secs);
$intObj = Math::BigInt->new($intObj->bmul('10 000 000'));
my $sixmonth_int = Math::BigInt->new(
$intObj->badd('116 444 736 000 000 000'));
$sixmonth_int =~ s/^[+-]//;
# Setup the ADO connections
my $connObj = Win32::OLE->new('ADODB.Connection');
$connObj->{Provider} = "ADsDSOObject";
$connObj->Open;
my $commObj = Win32::OLE->new('ADODB.Command');
$commObj->{ActiveConnection} = $connObj;
$commObj->Properties->{'Page Size'} = 1000;
# Grab the default root domain name
my $rootDSE = Win32::OLE->GetObject("LDAP://$domain/RootDSE");
my $rootNC = $rootDSE->Get("defaultNamingContext");
# Run ADO query and print results
my $query = "<LDAP://$domain/$computer_cont$rootNC>;";
$query .= "(&(objectclass=computer)";
$query .= "(objectcategory=computer)";
$query .= "(lastlogontimestamp<=$sixmonth_int));";
$query .= "cn,distinguishedName;";
$query .= "subtree";
$commObj->{CommandText} = $query;
my $resObj = $commObj->Execute($query);
die "Could not query $domain: ",$Win32::OLE::LastError,"\n"
unless ref $resObj;
print "\nComputers that have been inactive for $weeks_ago weeks or more:\n";
my $total = 0;
while (!($resObj->EOF)) {
my $cn = $resObj->Fields(0)->value;
print "\t",$resObj->Fields("distinguishedName")->value,"\n";
$total++;
$resObj->MoveNext;
}
print "Total: $total\n";
Partager