Often it is necessary to use the same DC to perform updates or errors will occur.
Here’s a way to do this which provides connection testing (is the DC online) that you don’t get with Get-ADDomainController.
This method finds a local DC running ADWS (Active Directory Powershell Web Service that runs on a DC) first, then checks a nearby site, then rolls through all the DCs (operating as GCs) until one is found.
Here’s the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import-module activedirectory Write-Output "Discovering local DC running Powershell ADWS `r " $TargetDC = (Get-ADDomainController -Discover -ForceDiscover -Service 6 ).HostName TRY { $DCCheck = Test-Path "\\$TargetDC\SYSVOL" } CATCH { Write-Output "Unable to connect to $TargetDC - Discovering a new DC `r " ; $DCCheck = $False } IF ($DCCheck -eq $False) { ## OPEN IF TargetGC is not set Write-Output "Discover DC running ADWS `r " $LocalSite = (Get-ADDomainController -Discover).Site $LocalDCs = Get-ADDomainController -Filter { (Site -eq $LocalSite) } ForEach ($DC.HostName in $LocalDCs) { ## OPEN ForEach DCHostName in LocalDCs $DCHostName = $DC.HostName $DCCheck = Test-Path "\\$DCHostName\SYSVOL" IF ($DCCheck -eq $True) { $TargetDC = $DCHostName ; break } } ## CLOSE ForEach DCHostName in LocalDCs } ## CLOSE IF TargetGC is not set IF (!$TargetDC) { ## OPEN IF TargetGC is not set Write-Output "Discover DC running ADWS `r " $AllDCs = Get-ADDomainController -Filter { IsGlobalCatalog -eq $True } ForEach ($DC.HostName in $AllDCs) { ## OPEN ForEach DCHostName in LocalDCs $DCHostName = $DC.HostName $DCCheck = Test-Path "\\$DCHostName\SYSVOL" IF ($DCCheck -eq $True) { $TargetDC = $DCHostName ; break } } ## CLOSE ForEach DCHostName in LocalDCs } ## CLOSE IF TargetGC is not set Write-Output "Setting DC target to $TargetDC `r " |