PowerShell Function: Validate Subnet Mask

This is a function I wrote couple of days ago for the Windows Build Scripts which I blogged yesterday. I think it is pretty cool so I’d like to blog this function individually:

image

It checks the following:

  • – if subnet mask is in numeric and consists 4 sections separated by “.”
  • – If each section is ranged between 0 and 255
  • – convert it to binary format and make sure it is a valid subnet mask (first part consists all “1”s and second part consists all “0”s).

So here’s the usage:

image

This function can be downloaded HERE

One comment

  1. If you use the parameter validation options in PowerShell, and appropriate object types, you can skip writing a lot of code to check the parameters by hand.
    The validation options will reject invalid input before it even reaches the body of the script.
    By using the System.Net.IPAddress type, you gain the handy feature of getting the individual bytes for free. And because they are bytes, you dont have to check if they are between 0 and 255.

    Below is a change version of your code. It’s not a 1 on 1 replacement, because it raises an error on invalid IP-adresses, instead of returning false.

    Function ValidateSubnetMask ([ValidateScript({
    #Sanity check because ([system.net.IPAddress]”192.168.1″).ToString() ==> 192.168.0.1
    If ($_ -match [IPAddress]$_) {
    $true
    } else {
    Throw “Cannot convert value "$_” to type "System.Net.IPAddress“. Error: "An invalid IP address was specified.“”
    }
    })]
    [String]$strSubnetMask
    )
    {
    #Check for IPV4 address
    If ([System.Net.IPAddress]$strSubnetMask.AddressFamily -ne ‘InterNetwork’) {Return $False}
    #Make sure it is actually a subnet mask when converted into binary format
    foreach ($item in ([System.Net.IPAddress]$strSubnetMask).GetAddressBytes())
    {
    $binary = [System.Convert]::ToString($item,2).PadLeft(8,”0″)
    $strFullBinary = $strFullBinary+$binary
    }
    If ($strFullBinary.Contains(“01”)) {Return $false}
    # next line can be removed if 0.0.0.0 and 255.255.255.255 are considered valid.
    If (($strFullBinary -Split “10”).Count -ne 2) {Return $false}

    Return $True
    }

    Also found another approach on the internet, but this one gives 0.0.0.0 and 255.255.255.255 as valid.

    function Test-IPv4MaskString {

    param(
    [parameter(Mandatory=$true)]
    [String] $MaskString
    )
    $validBytes = ‘0|128|192|224|240|248|252|254|255’
    $maskPattern = (‘^((({0})\.0\.0\.0)|’ -f $validBytes) +
    (‘(255\.({0})\.0\.0)|’ -f $validBytes) +
    (‘(255\.255\.({0})\.0)|’ -f $validBytes) +
    (‘(255\.255\.255\.({0})))$’ -f $validBytes)
    $MaskString -match $maskPattern
    }

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: