Powershell – determine the site boundary for a given IP

By DimitriC at January 25, 2010 23:53
Filed Under: Configuration Manager, Powershell

DETAILS
Let's say you have an IP address on a client 10.109.238.142, with subnet mask of 255.255.255.192.  What subnet is that address on? 
Well, in order to calculate that, the "book" says you take that first octet of the address and convert it to binary, and convert the first octet of the mask and convert it to binary, and then "AND" the bits together...well I'm going to spare you the bitwise lesson and just show you how you can do that using SQL.
The ampersand (&) character is the BITWISE AND operator in SQL.  When you have a number BITWISE ANDed with another number, it will use the bits of the first number and the bits of the second number and perform the operation on the bits themselves.  So using the first octet of our IP address and subnet, we would do 10 & 255.

An easy way to determine the site boundary for a system, given its IP and Subnet mask:

   1: $ip = "192.168.17.24"
   2: $subnetmask = "255.255.255.128"
   3:  
   4: $ips = $ip.split(".")
   5: $subnetmasks = $subnetmask.split(".")
   6: $boundary = $null
   7:  
   8: for ($i=0; $i -lt 4; $i++ )
   9: {
  10:     $boundary += [string]($ips[$i] -band $subnetmasks[$i])
  11:     if($i -lt 3)
  12:     {
  13:         $boundary += "."
  14:     }
  15: }
  16: $boundary
  17:  
  18: $colItems = get-wmiobject -class "Win32_NetworkAdapterConfiguration"
  19: #get only the adapter that is enabled
  20: $colitems | where {$_.IPEnabled -eq 1} | select IPAddress, ipSubnet
  21: #if ipAddress contains more then 1 element, check for xxx.xxx.xxx.xxx 
  22: #same goes for the subnet
  23: #pipe into the function to get the boundary
Comments are closed