TCP/IP subnet calculation applied. What Active Directory site is that server in? In a previous article, we showed how to calculate TCP/IP subnets with PowerShell. We've also showed how to list Active Directory sites and subnets. Now let's put those techniques together. This script tells you what Active Directory site a server is in.
The script takes one argument, a server name. The script then resolves the name to an IP address using a DNS query, and converts the result to binary. Next, the script gets all of the subnets defined in your AD, converts them to binary, and stores the binary subnet and the corresponding site name in a hash table.
Finally, the script tries to find a match between the server's IP address and the subnet, stripping off a bit at a time from the server's IP address until a match is found, or not. If a match is found, the name of the site is returned.
The script is useful in two ways. First, it identifies the site where a server is located, which is particularly useful if you're building a server inventory. Second, it will alert you if a server is on a subnet that is not defined in Active Directory.
function toBinary ($dottedDecimal){ $dottedDecimal.split(".") | %{$binary=$binary + $([convert]::toString($_,2).padleft(8,"0"))} return $binary }
if($args.count -ne 1){ "`nUsage: ./whatSite.ps1 <serverName>`n"; Exit; } $hostEntry= [System.Net.Dns]::GetHostByName($args[0]) if($hostEntry){ $ipAddress=toBinary ($hostEntry.AddressList[0].IPAddressToString) }else{ Write-Warning "Host not found!" Exit }
$sites=@{} $subnetsDN="LDAP://CN=Subnets,CN=Sites," + $([adsi] "LDAP://RootDSE").Get("ConfigurationNamingContext")
"`nGathering Site Information..." foreach ($subnet in $([adsi] $subnetsDN).psbase.children){ $site=[adsi] "LDAP://$($subnet.siteObject)" if($site.cn -ne $null){ ($networkID,$netbits)=$($subnet.cn).split("/") $binNetID=(toBinary $networkID).substring(0,$netbits) $sites[$binNetID]=([string]$site.cn).toUpper() } }
$i=32 do {$tryNetID=$ipAddress.substring(0,$i); if($sites[$tryNetID]){ "`n$($args[0]) is in site $($sites[$tryNetID])`n" Exit } $i-- } while ($i -gt 0)
Write-Warning "`n$($args[0]) is not in a defined site`n"
Related Posts:
- Backup DFS Namespaces Using PowerShell
- Translate Active Directory Name Formats Using PowerShell
- List Linux Users in Active Directory Using PowerShell
- Enable Trust for Delegation in Active Directory Using PowerShell
- TCP/IP Subnet Math with PowerShell - What AD Site is that Server in?
- List Sites and Subnets in Active Directory with PowerShell
- Find Disabled Users in Active Directory with PowerShell
- List Forest-wide Group Memberships with PowerShell
- Find Old Computer Accounts in AD with PowerShell
- List SPNs in Active Directory with PowerShell
- List Domain Controllers in Active Directory
0 comments:
Post a Comment