Last active
March 18, 2023 05:07
-
-
Save Mike-Crowley/3ad9472a2ab365c723f2272da197eabf to your computer and use it in GitHub Desktop.
Lookup what AD Site a given IP belongs to. Requires https://www.powershellgallery.com/packages/IP-Calc (https://web.archive.org/web/20230316203737/https://www.powershellgallery.com/packages/IP-Calc/3.1.0/Content/IP-Calc.ps1)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function Get-ADSiteByIp { | |
param ( | |
[parameter(Mandatory = $true)][ipaddress] | |
[ipaddress]$IP, | |
[bool]$CheckForScript = $true # faster | |
) | |
if ($CheckForScript -eq $true) { | |
try { Get-InstalledScript IP-Calc | Out-Null } | |
catch { | |
Install-Script -Name IP-Calc -Scope CurrentUser -Force -Confirm:$false | |
Write-Output "Installing IP-Calc.ps1 from https://www.powershellgallery.com/packages/IP-Calc" | |
try { Get-InstalledScript IP-Calc | Out-Null } | |
catch { | |
Write-Error "Unable to install required IP-Calc script" | |
throw | |
} | |
} | |
} | |
$domainDN = ($env:USERDNSDOMAIN -split '\.' | % { 'dc=' + $_ } ) -join ',' | |
$ConfigDN = (([adsi]"LDAP://$DomainDN").objectcategory -split 'Schema,')[-1] # forest-wide support | |
$Subnets = [ADSI]"LDAP://CN=Subnets,CN=Sites,$ConfigDN" | |
$selectFilter = @( | |
@{n = "SubnetFromSite"; e = { $_.name } } | |
@{n = "Site"; e = { ($_.siteObject -split ',' -replace 'CN=', '')[0] } } | |
@{n = "PrefixLength"; e = { (IP-Calc.ps1 -CIDR $_.name).PrefixLength } } | |
) | |
$siteSubnetDetail = $Subnets.Children | select $selectFilter | |
($siteSubnetDetail | where { (IP-Calc.ps1 $_.SubnetFromSite ).Compare($IP) } | sort PrefixLength)[-1] | select @{n = "InputIP"; e = { $IP } }, Site, SubnetFromSite | |
} | |
Get-ADSiteByIp -IP 10.1.1.1 -CheckForScript $false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment