I have been writing a script which does a lot of AD queries to find computer OUs. I wanted to do this on a close Global Catalog Server. Here is the function I wrote to get this:
Function Get-CloseGC{
#Requires -version 3
#requires -module ActiveDirectory
#it doesn't really require version 3 if you have AD module, but v2
#doesn't understand Requires -module
Import-Module ActiveDirectory
#Get this computer's AD site using .NET
$mySite = [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite()
#Get the DNS Root domain
$ADRoot = $(Get-AdDomain).DNSRoot
#Get enabled DCs which are GCs in MySite
[array]$DomainGCs = Get-ADDomainController -server $ADRoot `
-Filter {(Enabled -eq $true) -and (IsGlobalCatalog -eq $true)}
#Get GCs for this computer's AD site
[array]$MyGCs = $DomainGCs | Where-Object {$_.Site -eq $mySite}
#Get GC for mySite, if none available, pick first returned from DomainGCs
if ($MyGCs -ne $null) {
return $MyGCs[0].HostName
}ELSE{
Return $DomainGCs[0].HostName
}
}
Updated to take into account instances where a site GC is not available.
Update: 12/30/13: I spent some real world time with this code and was disappointed. I got better results by setting the server identity to just a domain name. Your mileage may vary…