- 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" |?{$_.name -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 + ".contoso.com/powershell/")
$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 microsoft.exchange -ConnectionUri $cURI -Authentication kerberos -Credential $credential
Import-PSSession $LocalExchSession