Monday, 20 April 2015

Efficient AD Queries

The cmdlets Get-AdUser and Get-ADComputer have a Filter parameter which is very powerful and can make a significant difference in script execution time.  Let’s take a look at how to use this parameter and what happens if you don’t (hint – it’s not good).

Spot the Difference

Take a look at these two lines of code.  They look quite similar at first glance but one is a beautiful one-liner and the other is a nightmare of inefficiency as you can see by their execution times.  The efficient one took 212 milliseconds while the inefficient one took 58 seconds!  In other words, the blink of an eye vs almost a full minute to retrieve the exact same information.  I like this example because it demonstrates how, armed with the right knowledge, subtle differences in how you write your scripts can make a massive difference in how efficient they are.

image

image

So why the big difference?  In the first example, we initially retrieve every single user account from AD (signified by –Filter *) and then we pass it through the pipeline and get our target user identified.  The Active Directory database that I ran this against had about 20,000 users in it so you can see why the query took so long – the script first retrieved all of those accounts and then had to go through each one, one at a time, to find the matching account.

Compare this to the second example where, instead of using an asterisk for the filter parameter, we specify the parameters of our search without piping the results to anything else for further processing.  By doing this, we allow AD to do the filtering for us and only return the result we require.  Since Active Directory is a database built for efficiently handling queries, we get our result back in a fraction of a second.

Another thing to keep in mind with this kind of thing is the difference in load you’re placing on the domain controller executing the query.  The first script places a much greater load on the poor DC handling the request because it has to retrieve and pass back every single account.  In the second script, the DC handles the query in the way it was born to do and the result is only a fraction of a second of work.  The filter parameter is your friend – use it!

No comments:

Post a Comment