Powershell check if ip or subnet belong to each other


I needed a powershell script today with which i can check if two given IP addresses match or if a given IP address belongs to a subnet or if a smaller subnet belongs to a larger one (or vise vursa). I found a nice script written by Sava from http://www.padisetty.com/ which had part of the functionality i required so i took and modified it to suit my needs. Below you will be able to find the modified script i hope it helps somebody :). The script will return an array of two values, one to indicate true or false and the second the direction.  The direction is important as you may want to compare values for a firewall and as such you want to fit one in the other in a particular direction.

Usage example:

  • checkSubnet ‘’ ‘’
  • checkSubnet ‘’ ‘′
  • checkSubnet ‘’ ‘’


5 thoughts on “Powershell check if ip or subnet belong to each other

  1. hi – Thanks very much for this function. This was perfect and fit-for-purpose where firewall rules are to be checked and validated

  2. This is a great script, but I did notice one thing. If you enter a CIDR format that has additional data beyond the mask it doesn’t provide the correct output. For example
    checkSubnet “” “” returns false although it is in the range. The unnecessary and ignored .1 in the second CIDR throws it off. I added some code to scrub the input and added it before the compare

    #Fix if a valid but incorrect entry is used (example
    if ($unetwork1 -ne ($unetwork1 -band $mask1))
    Write-Host “Mismatch between first argument address format and subnet mask, fixing” -ForegroundColor Red
    $unetwork1 = ($unetwork1 -band $mask1)
    if ($unetwork2 -ne ($unetwork2 -band $mask2))
    Write-Host “Mismatch between second argument address format and subnet mask, fixing” -ForegroundColor Red
    $unetwork2 = ($unetwork2 -band $mask2)

  3. To fix my own fix, my code fails if you enter in a single IP or CIDR that represents a single IP, so I moved this code into the If statement above that so it only runs if the -lt 32 condition is true. That has seemed to fix it and I have ran it on hundreds of subnets

Leave a Reply to Jeff Lawrence Cancel reply

Your email address will not be published. Required fields are marked *