Saturday, March 15, 2014

Ensuring your AD commands run against a local DC in PowerShell

When they finally, finally upgraded our workstations from Windows XP to Windows 7, I immediately installed all of the RSAT tools (Remote Server Administration Tools), including the PowerShell components and started playing with them.

It was nice to have native AD commands instead of having to install a third-party tool to fill the gap (so that we don't have to type the Q anymore, I guess).  But it was slow.  Slow, slow, slow.

But it wasn't the commands, it was my network.  I was working on a new network we were setting up, with slow WAN connections, and DNS had not yet been configured to preferentially return site-based results.  So my queries were sometimes going to domain controllers in Europe or Asia, or even the deep South.

I had to find a PowerShell trick to keep it local.

If we look for a domain controller first, the Get-ADDomainController command has a -Discover switch, which uses the DCLocator service instead of just DNS, and it's more intelligent about finding the closest DC.  I can't guarantee it will work in any environment, but for me it reliably returned a local DC.

So, query for a local DC, and then specify the DC in your subsequent AD queries.  As we had multiple domains, I also specified which one we wanted.

$DC = ( Get-ADDomainController -Discover -Domain Contoso.local ).HostName[0]
Get-ADUser -Filter { Name -like "Tim*" } -Server $DC

This trick came in handy recently to simplify a different problem.

I have been working with Microsoft Service Management Automation, which is PowerShell workflow based.  There are many interesting challenges to scripting in that environment.  One is that different parts of your script might run in different workflow or PowerShell instances (sometimes even on different “runbook worker” servers).  That means different AD commands may run against different domain controllers, which adds the complication of AD replication latency.  The simple solution is to use the command above to pick a single domain controller to run all of your related commands against.

No comments:

Post a Comment