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  :

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
  return $result;

PS > Convert-IpAddressToMaskLength
PS > Convert-IpAddressToMaskLength

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


    • 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. (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 on the example provided.

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

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.