Skip to content

Instantly share code, notes, and snippets.

@phwelo
Last active April 23, 2018 20:11
Show Gist options
  • Save phwelo/011356ed01f6fc81de6deb4a7d5e7207 to your computer and use it in GitHub Desktop.
Save phwelo/011356ed01f6fc81de6deb4a7d5e7207 to your computer and use it in GitHub Desktop.
Loop through all computers in an active directory domain
$ADDomain = 'domain.local'
if((Get-ADDomain -Current LocalComputer) -like "$ADDomain"){
Write-Host "Credentials will be inherited from logged in session"
$ADDomain_Obj = Get-ADDomain $ADDomain
} else {
$Credential= Get-Credential -Message "Enter credentials for $ADDomain"
$ADDomain_Obj = Get-ADDomain $ADDomain -Credential $Credential
}
$DC_OU = $ADDomain_Obj.DomainControllersContainer
$PDC = $ADDomain_Obj.InfrastructureMaster
$Domain_Controllers = get-adcomputer -searchbase $DC_OU -filter * -Server $PDC
$PingTimes = @{}
foreach($Domain_Controller in $Domain_Controllers) {
$PingTimes.add([string]($Domain_Controller.DNSHostName), [int](Test-NetConnection -ComputerName ($Domain_Controller).DNSHostName).PingReplyDetails.RoundTripTime)
}
$PingTimes = $PingTimes | Sort-Object
$SortedDCList = $PingTimes.Keys
$QuickestDC = $SortedDCList | Select -First 1
$AllComputers = Get-ADComputer -Server $QuickestDC -Filter *
foreach($Computer in $AllComputers) {
write-host $($AllComputers.DNSHostName) # Your stuff goes here
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment