Nearest Domain Controller without Powershell AD Module

Getting the nearest Domain Controller when the AD module is present, is fairly simple, all you would need to do is running the following:

But what if you want to achieve the same result on a client/server that doesn’t have the Powershell Active Directory modules installed?
Well, in cmd you can do something like this:

The above will come back with quite a few useless (to our scope) pieces of information (or an error).

dsgetdc-nearest-domain-controller-1

 

So we can run this instead, to just get the “DC”:

So now we have just one line with the Domain Controller (or the error).

dsgetdc-nearest-domain-controller-2

Now, let’s try to work with the above command in powershell. What we want to achieve is having a variable ($DC) that will either contain the domain controller name or any other value that we want if there’s an error, for instance we could assign the value $false to it.

The script is pretty crude so that you can modify it as you like; let’s explain what it does. It first tries to run the above command with a slight difference, I added .split(” “) that will automatically split the result in an array of sub-strings. But, if the command fails, this powershell command won’t be able to split anything and will throw an error. This is why we need a Try/Catch.
If the command fails to retrieve a domain controller then, $DC will be $false.
Now, if the .split command works, then the script runs through each object of the array of sub-strings and checks when the sub-string starts with two backslashes: that means that we’ve got what we’re looking for!.
Finally, $DC will get the name of the domain controller assigned . Note that .replace(‘\\’,”) will remove the two backslashes and will leave us just the domain controller’s hostname.
I hope this explains a bit more the idea behind it.

Leave a Reply

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