Skip to main content

Active Directory Searcher - Part 1

One of the first things I learnt to do in powershell was to search AD. I could search in VB but there were a few quirks and limitations that gave me the incentive to take the leap in to PS. That and I had just started a new job supporting a large financial AD environment where we had to do a lot of data capture across multiple domains!

As anyone would, I looked at the way VB works and tried to convert it. Here is a direct translation of VB to PS in terms of searching AD ...

VB Script :

Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
objCommand.CommandText = "<LDAP://dc=other,dc=com>;(objectclass=user);name;subtree"
Set objRecordSet = objCommand.Execute

If objRecordset.RecordCount > 0 Then
   Do Until objRecordSet.EOF
      wscript.echo objRecordSet.Fields("name")
End If

which converts to :

$objConnection = New-Object -comObject "ADODB.Connection"
$objCommand = New-Object -comObject "ADODB.Command"
$objCommand.ActiveConnection = $objConnection
$objCommand.CommandText = "<LDAP://dc=other,dc=com>;(objectclass=user);name;subtree"
$objRecordSet = $objCommand.Execute()
if ($objRecordSet.pagesize -gt 0){
   Do {
      $objRecordSet.Fields.item("name") | Select-Object Value
   Until ($objRecordSet.eof)

And there we have it, how to write VB in powershell! Actually there is more to powershell than using the same tools that you would use in VB. Here is where one of my resource links comes in handy ... let’s explore .net.

Where we would use the ADODB commands of old, they can be replaced with the .net object :


Which can be used in the following way (note this is a one line command, it may have wrapped on to multiple lines in this blog) :

$Searcher = New-Object System.DirectoryServices.DirectorySearcher("LDAPdomain", "LdapQuery","properties","searchscope")

You may see a similarity to the commandtext line in the ADODB way of connecting. I have specifically used the “constructor” in the .net class that accepts 4 arguments to match ADODB as closely as possible. You can create an empty object and populate the options later. See this link for all available constructors.

The LDAPdomain needs to be a DirectoryEntry object, and the other 3 need to be strings. The strings are pretty easy, but how do I get a DirectoryEntry object? The answer is there are many ways, it all depends where you are in your script and what objects you have. When you only have an LDAP path to the entry you want to retrieve, the most standard way is to call the .net class as we did with the $Searcher (again, one line command) :

$LDAPdomain = New-Object System.DirectoryServices.DirectoryEntry('LDAP://dc=other,dc=com')

There is, however, a neat little shortcut in powershell which you can use :

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

Obviously, you have to define this prior to creating the searcher so at the moment, using the same options as our VB example our script looks like this :

$LDAPdomain = [ADSI]('LDAP://dc=other,dc=com')
$Searcher = New-Object System.DirectoryServices.DirectorySearcher($LDAPdomain,"(objectclass=user)","name","subtree")

We have set up the searching mechanism, now let’s run the search...

$Results = $Searcher.FindAll()

... and loop through the results using a foreach cmdlet :

foreach ($Object in $Results){

Note, the use of $ rather than $ I have fallen foul a few times to this and then was very confused to why I was not getting any values back.

So, the complete 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){

Quite neat and tidy! That’s it for part 1, Part 2 will take things a bit further by looking into pulling information from AD rather than hard coding variables, other options you can specify and how to deal with certain types of values returned.


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

In v3 the same test returns true....

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

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



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 - 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 -, - …

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…