Powershell : IP Lookup to ADDS Site


This is a simple script for simple requirements, when you are asked by people "Do we have that IP address in Active Directory sites and services?" you have to open the plugin and manually check the IP range listing to see if there is a site that matches.

What if you could do this with a script, well that is what this script does, where it takes the IP address the full IP like 10.266.11.22/32 and the script then lookups up that IP address to see if it matches a "Site"

You simply run it with the syntax:

IP2Site.ps1 -IPAddress <ipaddress>

That looks like this:


Script : IP2Site.ps1

#Requires -Modules ActiveDirectory
[CmdletBinding()]
param (
    [Parameter(Mandatory = $true, Position = 0)]
    [ValidatePattern("^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")]
    [string]$IPAddress
)

function Test-IPInSubnet {
    param (
        [string]$IPAddress,
        [string]$SubnetCIDR
    )

    # Split subnet CIDR into network and prefix
    $subnetParts = $SubnetCIDR.Split('/')
    $subnetIP = $subnetParts[0]
    $prefixLength = [int]$subnetParts[1]
    # Convert IP addresses to byte arrays
    $ipBytes = ([System.Net.IPAddress]::Parse($IPAddress)).GetAddressBytes()
    $subnetBytes = ([System.Net.IPAddress]::Parse($subnetIP)).GetAddressBytes()

    # Convert to 32-bit integers
    $ipInt = 0
    $subnetInt = 0
    for ($i = 0; $i -lt 4; $i++) {
        $ipInt = ($ipInt -shl 8) + $ipBytes[$i]
        $subnetInt = ($subnetInt -shl 8) + $subnetBytes[$i]
    }

    # Calculate subnet mask
    $mask = -bnot ((1 -shl (32 - $prefixLength)) - 1)

    # Check if the IP is in the subnet
    ($ipInt -band $mask) -eq ($subnetInt -band $mask)
}

function Get-FormattedSiteInfo {
    param (
        [Microsoft.ActiveDirectory.Management.ADObject]$Site
    )

    $siteInfo = [ordered]@{
        "Name" = $Site.Name
        "Description" = $Site.Description
        "Location" = $Site.Location
        "DistinguishedName" = $Site.DistinguishedName
    }

    # Get site links for this site
    try {
        $siteLinks = Get-ADReplicationSiteLink -Filter * | Where-Object { $_.SitesIncluded -contains $Site.DistinguishedName }
        if ($siteLinks) {
            $siteInfo["SiteLinks"] = @($siteLinks | ForEach-Object { $_.Name })
        }
    }
    catch {
        Write-Verbose "Unable to get site links: $_"
    }
    return $siteInfo
}
function Get-ADSiteForSubnet {
    param (
        [string]$SubnetName
    )
    $subnet = Get-ADReplicationSubnet -Filter "Name -eq '$SubnetName'" -Properties Site
    if ($subnet -and $subnet.Site) {
        $site = Get-ADReplicationSite -Identity $subnet.Site -Properties Description, Location
        if ($site) {
            return Get-FormattedSiteInfo -Site $site
        }
    }
    return $null
}

# Main script execution
try {
    # Ensure the ActiveDirectory module is available
    if (!(Get-Module -ListAvailable -Name ActiveDirectory)) {
        Write-Error "The ActiveDirectory PowerShell module is required but not installed. Please install it and try again."
        exit 1
    }
    Write-Host "Checking if IP address $IPAddress belongs to any AD subnet..." -ForegroundColor Cyan

    # Get all subnets from AD
    $adSubnets = Get-ADReplicationSubnet -Filter * -Properties Description

    if (!$adSubnets -or $adSubnets.Count -eq 0) {
        Write-Host "No subnets found in Active Directory." -ForegroundColor Yellow
        exit 0
    }
    $matchingSubnets = @()
    foreach ($subnet in $adSubnets) {
        if (Test-IPInSubnet -IPAddress $IPAddress -SubnetCIDR $subnet.Name) {
            $matchingSubnets += $subnet
        }
    }
    if ($matchingSubnets.Count -eq 0) {
        Write-Host "The IP address $IPAddress does not belong to any subnet defined in Active Directory." -ForegroundColor Yellow
    }
    else {
        Write-Host "The IP address $IPAddress belongs to the following subnet(s):" -ForegroundColor Green
        foreach ($subnet in $matchingSubnets) {
            $siteInfo = Get-ADSiteForSubnet -SubnetName $subnet.Name           
            Write-Host "`nSubnet: $($subnet.Name)" -ForegroundColor Green
            Write-Host "Description: $($subnet.Description)" -ForegroundColor Gray           
            if ($siteInfo) {
                Write-Host "`nAssociated Site Information:" -ForegroundColor Cyan
                foreach ($key in $siteInfo.Keys) {
                    if ($siteInfo[$key] -is [array]) {
                        Write-Host "  ${key}:" -ForegroundColor Gray
                        foreach ($value in $siteInfo[$key]) {
                            Write-Host "    - $value" -ForegroundColor Gray
                        }
                    }
                    else {
                        Write-Host "  ${key}: $($siteInfo[$key])" -ForegroundColor Gray
                    }
                }
            }
            else {
                Write-Host "`nNo site associated with this subnet." -ForegroundColor Yellow
            }
        }
    }
}
catch {
    Write-Error "An error occurred: $_"
    exit 1
}

You will then get an output that will tell you the site as below (yes its been redacted):


Previous Post Next Post

نموذج الاتصال