top of page
  • ExchangeMaster

Pick a Responsive Domain Controller for Your Script

Updated: Apr 20, 2021

To avoid unpredictable results due to your script reading from or writing to "random" domain controllers, it's good practice to use the -Server or -DomainController parameter pertinent to a given cmdlet. Typing the parameter and the hostname is a pain though, and it's tempting to avoid the effort and just roll the dice. The fragment below supplies your script a consistent, responsive DC upon launch. It saves you some typing up front, and potentially some editing later on, should a DC become unavailable (planned or otherwise).

# Insert the domain controllers in CHI or NYC into an array, then select the first one which responds to test.
$dcList = Get-ADDomainController -Filter {name -like 'CHI*' -OR name -like 'NYC*'} | select -ExpandProperty hostname
$dcCount = ($dcList).count
$dcIteration = 0
DO {
if($dcIteration -le $dcCount){
 $dc = $dclist[$dcIteration]
 $dcTest = Test-Connection -ComputerName $dc -BufferSize 16 -Count 1 -Quiet -ErrorAction SilentlyContinue
 $dcIteration = $dcIteration++}
} Until($dcTest = 'True')

$dc is the variable you'd then use with the -Server or -DomainController parameters. Note that you'll need to change the $dcList line to match your naming convention, add additional -OR statements, etc.

You can also use similar language to pick an Exchange server, if that's relevant to your purpose.

# Insert the Exchange servers into an array, then select the first one which responds to test.
$exList = Get-ADGroupMember -Identity "Exchange Servers" |?{$ -notlike "*install*"}| select -ExpandProperty name
$exCount = ($exList).count
$exIteration = 0
DO {
if($exIteration -le $exCount){
 $ex = $exlist[$exIteration]
 $exTest = Test-Connection -ComputerName $ex -BufferSize 16 -Count 1 -Quiet -ErrorAction SilentlyContinue
 $cURI = ("http://" + $ex + "")
 $exIteration = $exIteration++}
} Until($exTest = 'True')

You can then use $cURI to setup your PowerShell session with an on-prem Exchange server. For example:

$LocalExchSession = New-PSSession -ConfigurationName -ConnectionUri $cURI -Authentication kerberos -Credential $credential
Import-PSSession $LocalExchSession


53 views0 comments

Recent Posts

See All

Recently I needed a quick script to set the two-letter O365 country codes, while my only source for the setting was the three-letter codes in a given AD forest. This presented a problem, because O365

bottom of page