Skip to main content

Active Directory Searcher - Part 2

We finished up Part 1 with this script :


$LDAPdomain = [ADSI]('LDAP://dc=other,dc=com')

$Searcher = New-Object System.DirectoryServices.DirectorySearcher($LDAPdomain,"(objectclass=user)","name","subtree")
$Results = $Searcher.FindAll()
foreach ($Object in $Results){
  $Object.Properties.name
}
I am going to take things a little further by adding variables which in turn will help remove any hardcoded elements of the script.

A quick one first, after running your search for all users, did you notice that you got exactly 1000 results (assuming that you have at least 1000 users in your domain)?  This is the maximum number of records that you can return in one go using LDAP.  What you need to do is tell the searcher to page results by adding this command :

$Searcher.pagesize = 1000
This will return the first 1000, but go off and find the next 1000 straight after, and so on.


The next thing is to use variables instead of hard coding in the new-object line.  Apart from making edits to your code easier (especially if you are handing the script over to someone less familiar with powershell), this has other benefits as you will see later :




$ObjectCategory = "user"
$ObjectProplist = "name","samaccountname","whencreated"
$LdapQuery = "(&(objectCategory=$ObjectCategory)(name=ad*))"
$LDAPdomain = [ADSI]('LDAP://dc=other,dc=com'$Searcher = New-Object System.DirectoryServices.DirectorySearcher($LDAPdomain, $LdapQuery, $ObjectProplist, "subtree")


$Searcher.pagesize = 1000
$Results = $Searcher.FindAll()
etc...
Not too trickey eh?  As we now have all variables for the searcher object, lets look at getting rid of the hard coded domain name.  This becomes very handy if you have multiple forests to manage and search as the same code will work across them all.  We have to go back to .net to do this.


We have 2 classes we can use, System.DirectoryServices.ActiveDirectory.forest or System.DirectoryServices.ActiveDirectory.domain. If you use forest, you can then search each domain in the forest, or you can target just a single domain with domain.  The constructor I find i use most is 


$domains = [System.DirectoryServices.ActiveDirectory.forest]::getcurrentforest().get_domains()
I use the forest class and call the getcurrentforest() method, which (funnily enough) gets the current forest.  Now, the beauty of  powershell is that you don't have to store that in a variable if you don't need to, you can just call the method straight from the forest object get_domains() and store them.  This is essentially a quick way of doing this :

$forest = [System.DirectoryServices.ActiveDirectory.forest]::getcurrentforest()
$domains = $forest.get_domains()

So what we are left with is an array of how ever many domains are in your forest ready for you to do a foreach-object against.  Remember in part 1 I said that there were many way of getting a directory entry object, well here is another one. When we loop round our array of domain objects, we can call the method $domain.getdirectoryentry() to pass to our searcher.  This removes the hard coded domain and makes things a lot simpler. 

$domains = [System.DirectoryServices.ActiveDirectory.forest]::getcurrentforest().get_domains()
$ObjectCategory = "user"
$ObjectProplist = "name","samaccountname","whencreated"
$LdapQuery = "(&(objectCategory=$ObjectCategory)(name=ad*))"
foreach ($domain in $domains){
      ($domain).name
      $LDAPdomain = $domain.GetDirectoryEntry()
      $Searcher = New-Object System.DirectoryServices.DirectorySearcher($LDAPdomain, $LdapQuery, $ObjectProplist,"subtree")
      $Searcher.pagesize = 1000
      $Results = $Searcher.FindAll()
      foreach ($Object in $Results){
           $Object.Properties.name
      }
}

Cool!  No more hard coding.  ahhhhh but there is.  We are only outputting the name property, what about the other properties in the list?  Here's where using a variable starts to be handy.  You can do a foreach loop for every object in the array any output everything you have searched for, and all by only changing the $objectproplist array : 



$domains = [System.DirectoryServices.ActiveDirectory.forest]::getcurrentforest().get_domains()
$ObjectCategory = "user"
$ObjectProplist = "name","samaccountname","whencreated"
$LdapQuery = "(&(objectCategory=$ObjectCategory)(name=ad*))"
foreach ($domain in $domains){
      ($domain).name
      $LDAPdomain = $domain.GetDirectoryEntry()
      $Searcher = New-Object System.DirectoryServices.DirectorySearcher($LDAPdomain, $LdapQuery, $ObjectProplist,"subtree")
      $Searcher.pagesize = 1000
      $Results = $Searcher.FindAll()
      foreach ($Object in $Results){
            foreach ($prop in $ObjectProplist){
                  $Object.Properties.$prop
                 }
      }
}
I will be finishing up with Part 3 looking at a few techniques in how to better deal with the information gathered including using switch statements, traps and outputting the information to an array proir to exporting to CSV.

Comments

Popular posts from this blog

PowerShell 3 behavioural change

It's taken me way too long to get into PowerShell 3, I guess opportunity hasn't shown it's self until now and so, here, my V3 journey begins.

I was asked to debug a script that would run fine in PS v2 and not in v3.  The issue was a that a variable length was being checked and was failing in v3.  This is why...

In v2 if a variable is undefined, this test returns false

PS C:\windows\system32> $var.length -eq 0
False

In v3 the same test returns true....

PS C:\windows\system32> $var.length -eq 0
True

Not a biggie, but as in this case, a script has broken so something to consider!

cheers

Adam

Enable Powershell Remoting (WinRM) via Group Policy

I have been doing some testing on enabling WinRM via group policy, being that WinRM is the service that Powershell v2 sets up it remoting capabilities. Here are the GPO settings that you need to configure WinRM ....


set the winrm service to auto start


Computer Configuration \ Policies \ Windows Settings \ Security Settings \ System Services


Windows Remote Management (WS-Management)  set Startup Mode to Automatic

start the service


incorporated in to the above - you may need a restart.


create a winrm listener


Computer Configuration / Policies / Administrative Templates / Windows Components / Windows Remote Management (WinRM) / WinRM Service / Allow automatic configuration of listeners


IPv4 filter: *


* is listen on all addresses, or if you only want a particular IP address to respond use an iprange eg 10.1.1.1-10.1.1.254 - don't forget that this IP range has to be valid for all hosts that fall in the scope of the GPO you are creating.  You can use 10.1.1.1 - 10.1.1.254,10.1.1.3 - 10.1.4.254 …

compare-object in Powershell - comparing mulitple values

I'm starting to use compare-object more and more, and one thing I noticed, is that you can compare 2 objects based on multiple attributes. here is how it is constructed...
Compare-Object -ReferenceObject $object1 -DifferenceObject $object2 -Property a,b,c,d,eIf a,b,c and d are the same, but e is different, compare object will return a difference. In the following example, I use "-eq $null" as a check because by default compare-object returns $null if the objects are the same.
#create an array of objects to check against

$collection = @()
foreach ($entry in ("aaaaa","bbbbb","ccccc","ddddd")){
   $store = "" | select "a","b","c","d","e"
   $store.a = $entry*1
   $store.b = $entry*2
   $store.c = $entry*3
   $store.d = $entry*4
   $store.e = $entry*5
   $collection += $store
}

#create an object similar to those in the array
$object = "" | select "a","b…