use Win32::OLE qw (in);                # base functionality
use Win32::OLE::Variant;

query_ldap("<LDAP://OU=someou,dc=somedomain,dc=com>;(&(objectclass=User)(whenCreated=*));adspath,cn,whenCreated;subtree",$objects);

print "recordcount = ".$objects->{RecordCount}."\n";
while (!$objects->{EOF}) {
  print $objects->Fields("adsPath")->{Value}." --" . $objects->Fields("whenCreated")->{Value} ."\n";
  $objects->MoveNext();
}

sub query_ldap {
  my $ldap_query = $_[0];

  my $error_num;
  my $error_name;
  my $RS;
  my $Conn = Win32::OLE->new("ADODB.Connection");
  if (Win32::OLE->LastError() != 0) {
    print "Failed creating ADODB.Connection object (".Win32::OLE->LastError().")\n   -> $ldap_query\n";
    return 0;
  }
  $Conn->{'Provider'} = "ADsDSOObject";
  if (Win32::OLE->LastError() != 0) {
    print "Failed setting ADODB.Command Provider (".Win32::OLE->LastError().")\n   -> $ldap_query\n";
    return 0;
  }
  $Conn->{Open} = "Perl Active Directory Query";

  my $Cmd = Win32::OLE->new("ADODB.Command");
  if (Win32::OLE->LastError() != 0) {
    print "Failed creating ADODB.Command object (".Win32::OLE->LastError().")\n   -> $ldap_query\n";
    return 0;
  }
  $Cmd->{CommandText} = $ldap_query;
  $Cmd->{Properties}->{"Page Size"} = 99;
  $Cmd->{ActiveConnection} = $Conn;
  $RS = $Cmd->Execute();
  if (Win32::OLE->LastError() != 0) {
    print "Failed Executing ADODB Command object (".Win32::OLE->LastError().")\nExecuting ADODB Command -> $ldap_query\n";
    return 0;
  } else {
    $_[1] = $RS;
    return 1;
  }
}

