With PowerShell 3.0 and onwward you can easily convert a SubnetMask in bit form to a “real” dotted 4 octet format:

PS > $MaskLength = 24;
PS > [IPAddress] $ip = 0;
PS > $ip.Address = ([UInt32]::MaxValue -1) -shl (32 - $MaskLength) -shr (32 - $MaskLength)
PS > $ip

Address            : 16777215
AddressFamily      : InterNetwork
ScopeId            :
IsIPv6Multicast    : False
IsIPv6LinkLocal    : False
IsIPv6SiteLocal    : False
IsIPv6Teredo       : False
IsIPv4MappedToIPv6 : False
IPAddressToString  : 255.255.255.0

Reverting that operation is a bit trickier, but easily handable as well:

function Convert-IpAddressToMaskLength([string] $dottedIpAddressString)
{
  $result = 0; 
  # ensure we have a valid IP address
  [IPAddress] $ip = $dottedIpAddressString;
  $octets = $ip.IPAddressToString.Split('.');
  foreach($octet in $octets)
  {
    while(0 -ne $octet) 
    {
      $octet = ($octet -shl 1) -band [byte]::MaxValue
      $result++; 
    }
  }
  return $result;
}

PS > Convert-IpAddressToMaskLength 255.254.0.0
15
PS > Convert-IpAddressToMaskLength 255.255.128.0
17

UPDATE: be careful when trying to convert IP addresses with leading zeros, as described in this post.

8 Comments »

    • Hi Christopher, thanks for your hint – very much appreciated! I corrected the error and it seems to be working correctly now.
      Regards, Ronald

  1. I am interested int this…. however, I am a powershell noobie. How do you run this? And do you run it against a file? If so, what format does the IP addressing need to be in?

    • `Convert-IpAddressToMaskLength` is a PowerShell function, which you can run directly from the console once you have defined it. Defining the function can be either done by simply pasting it into the console or by “dot-sourcing” it from a file. The format of the IP address would be “dotted”, e.g. 255.254.0.0 (like written in the blog post). If you want to convert multiple IP addresses you can put them into a file (one by a line) and then read them with `Get-Content` and pipe them to the method like this: `Get-Content myAddresses.txt | % { Convert-IpAddressToMaskLength $_ }`. For details on “dot-sourcing” etc have a look at StackOverflow.com or similar QA sites.

  2. The original bit of code doesn’t work either. On PS 5.1 the resulting IPAddressToString turns out to be 254.255.255.0 on the example provided.

      • That works but only for full 255 values. If you do something like /10 you get 254.3.0.0 but it should be 255.192.0.0

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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