Specifying a single domain controller while keeping redundancy in a PowerShell script

When scripting against Active Directory I usually specify a domain controller for the “-Server” parameter of the AD cmdlets to prevent potential issues with replication.

For example, say you are creating a new group, and then want to change the ACLs of that group, for example the “WriteMembers”-permission. You probably want to specify the same domain controller on these two requests to make sure the newly created group is actually available when changing the ACL.

But hard coding things are usually not a good idea, and if that DC happens to go offline while a script is running, a lot of requests might fail. So what I did was to create a function that checks if the specified DC is online, and if it isn’t, it retrieves a lists of all the DCs that exists in the same site as the server where the script is executing, and picks the next available one after verifying it works.

Usage example:

PS> Get-ScriptDC -PreferedDC MyDC01.MyDomain.local
WARNING: Failed to connect to MyDC01.MyDomain.local.

In this case, MyDC01.MyDomain.local was offline and didn’t work, so the function instead returned MyDC02.MyDomain.local which has been verified by issuing a AD-query to it. It is simply returned as a string, so to use it in a script you could do something like this (with some errorhandling added):

$MyPreferedDC = 'MyDC01.MyDomain.local'
$DCToUse = Get-ScriptDC -PreferedDC $MyPreferedDC

Get-ADUser JohnDoe -Server $DCToUse

If you put this first in the script, you’ll know that the DC used will be online when the script starts, if you want to, you could of course run this function again within in a catch-statement to be able to “failover” to another DC during script execution.

The code for this function has been uploaded to PoshCode.org here.

The ActiveDirectory-module must be available for it to work.

Leave a Reply

Your email address will not be published. Required fields are marked *