Skip to content

Instantly share code, notes, and snippets.

@Mike-Crowley
Last active March 18, 2023 05:07
Show Gist options
  • Save Mike-Crowley/3ad9472a2ab365c723f2272da197eabf to your computer and use it in GitHub Desktop.
Save Mike-Crowley/3ad9472a2ab365c723f2272da197eabf to your computer and use it in GitHub Desktop.
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