Wednesday, 7 October 2015

PowerShell Function to Return Correct Subnet

A quickie function I wrote to find the correct subnet e.g.:

PS C:\ > return-correctsubnet 10.11.12.13/22
10.11.12.0/22
PS C:\ > return-correctsubnet 11.11.11.11/22
11.11.8.0/22

The script:

Function Find-OctetBit{
  Param([Int]$Octet,[Int]$SubnetBit)
  $ModuloOctet = $Octet
  $ModuloOctet %= 256/([math]::Pow(2,$SubnetBit))
  $Octet -= $ModuloOctet
  RETURN $Octet
}

Function Return-CorrectSubnet {
  Param([String]$ClientMatch)
  If($ClientMatch -match "/"){
    [System.Array]$Octet = $ClientMatch.Split("/")[0].Split(".")
    If( $Octet.Count -ne 4 ){ RETURN $ClientMatch }
    [Int]$Subnet = $ClientMatch.Split("/")[1]
    If     ($Subnet -ge 24){ $ClientMatch = $Octet[0] + "." + $Octet[1] + "." + $Octet[2] + "." + [String](Find-OctetBit $Octet[3] ($Subnet -24)) + "/" + [String]$Subnet }
    elseif ($Subnet -ge 16){ $ClientMatch = $Octet[0] + "." + $Octet[1] + "." + [String](Find-OctetBit $Octet[2] ($Subnet -16)) + ".0/" + [String]$Subnet }
    elseif ($Subnet -ge 8) { $ClientMatch = $Octet[0] + "." + [String](Find-OctetBit $Octet[1] ($Subnet -8)) + ".0.0/" + [String]$Subnet }
    else                   { $ClientMatch = [String](Find-OctetBit $Octet[0] ($Subnet -0)) + ".0.0.0/" + [String]$Subnet }
  }
  RETURN $ClientMatch
}

No comments:

Post a Comment