Sometimes when you run scripts that rely on AD replication for subsequent steps to be successful, you will be better off not relying on AD replication but just running all commands against a single Domain Controller.
This handy little one-liner will help you assign a local domain controller to a variable and then use it throughout your script.
The command does the following:
1. Find out the DNS Root of your local domain.
2. Use that to find out all the servers in your local site.
3. Ping all of them at once.
4. Output the name of the first server that responds.
This is the command:
(Test-Connection (([System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite()).Servers | ?{$_.Domain -like "$((Get-ADDomain).DNSRoot)"}).Name | select -first 1).Address
Breakdown of the command:
([System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite())
– Gets your current AD Site
?{$_.Domain -like "$((Get-ADDomain).DNSRoot)"}
– Uses where-object to filter out any domains that aren’t your primary dns root domain.
(([System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite()).Servers | ?{$_.Domain -like "$((Get-ADDomain).DNSRoot)"}).Name
– The two commands above combined to spit out a list of servers in the domain.
Test-Connection is run against this list and then we use Select -First 1 to only use the first server that responds.