<# Find-ADsiteFromIP.ps1 Alan Kaplan 11/30/2018 #> #Clear variables $errmsg = $site = $subnet = $dcList = '' Write-Host "This script will get the AD site and DC(s) for an IP address" $TestIP = Read-Host -Prompt "Enter an IP v4 address" #Get site using NLTest, convert to object $NLTretval = nltest /dsaddresstosite:$TestIP 2> $null if ($NLTretval[2].length -eq 1) { $errmsg = "Could not find site for $testIP" } else { $a = [regex]::Split($NLTretval[2].Trim(), ' ') $site = $a[1] $Subnet = $a[2] } if ($Subnet -match 'null') { $errmsg = "Could not find defined subnet for $testIP" } if ($errmsg -eq '') { #Get ConfigurationNamingContext $objRootDSE = [System.DirectoryServices.DirectoryEntry] "LDAP://rootDSE" $ConfigurationNC = $objRootDSE.configurationNamingContext #Search Sites $Searcher = New-Object System.DirectoryServices.DirectorySearcher $Searcher.SearchScope = "subtree" $Searcher.SearchRoot = "LDAP://CN=Sites`,$ConfigurationNC" #Get list of all servers $searcher.Filter = "(objectclass=Server)" $siteInfo = ($Searcher.FindAll()) #filter for AD path results $filter = '*CN=' + $Site + '*' #Concatenate server names $dcList = ( (($siteInfo | Where-Object {$_.path -like $filter}).properties.name)| Sort-Object ) -join ', ' } #PS Custom Object $NLTinfo = [PSCustomObject]@{ IP = $TestIP Subnet = $Subnet Site = $site 'DC List' = $dcList Errors = $errmsg } $NLTInfo Pause