Last active
May 6, 2023 11:51
-
-
Save ArmaanMcleod/dbb5e1d29b6fec9b8bdcbd54d9f7ff1a to your computer and use it in GitHub Desktop.
PowerShell Subnet Overlap
This file contains hidden or 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 ConvertTo-IPv4MaskString { | |
[CmdletBinding()] | |
param( | |
[Parameter(Mandatory = $true)] | |
[ValidateRange(0, 32)] | |
[int] | |
$MaskBits | |
) | |
$mask = ([System.Math]::Pow(2, $MaskBits) - 1) * [System.Math]::Pow(2, (32 - $MaskBits)) | |
$bytes = [System.BitConverter]::GetBytes([UInt32] $mask) | |
(($bytes.Count - 1)..0 | ForEach-Object { [string] $bytes[$_] }) -join '.' | |
} | |
function Test-SubnetOverlap { | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory = $true)] | |
[string] | |
$Subnet1, | |
[Parameter(Mandatory = $true)] | |
[string] | |
$Subnet2 | |
) | |
$subnetParts1 = $Subnet1.Split('/') | |
$subnetParts2 = $Subnet2.Split('/') | |
$address1 = [System.Net.IPAddress]($subnetParts1[0]) | |
$address2 = [System.Net.IPAddress]($subnetParts2[0]) | |
$mask1 = [System.Net.IPAddress]::Parse((ConvertTo-IPv4MaskString -MaskBits ([int]($subnetParts1[1])))) | |
$mask2 = [System.Net.IPAddress]::Parse((ConvertTo-IPv4MaskString -MaskBits ([int]($subnetParts2[1])))) | |
($address1.Address -band $mask1.Address) -eq ($address2.Address -band $mask2.Address) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tests if two subnets overlap e.g.