Category Archives: powershell

Set your Powershell scripts to always use the closest Domain Controller

When writing a new script, I like to make sure I know which DC my AD cmdlets are talking to. I do this by using the -Server flag, but rather than hard-coding a specific DC into my scripts, I always use the closest writable DC by starting all my scripts with this line:

$domainController  = (Get-ADDomainController -Writable -Discover -NextClosestSite).name

You’ll then specify this DC when you’re making your AD calls:

Get-ADUser -identity 'Benjamin Atman' -server $domainController

Starting your scripts this way will ensure you’re always talking to the closest DC, and that you always know which one you’re talking to.