Search code examples
powershellnetworkingcidr

How do I convert a network address with mask to CIDR-notation using PowerShell?


I did find a lot of examples about how to convert CIDR to a network mask, but not the other way around (at least not using PowerShell).

So getting the data to start working which is easy

$ActiveNic = Get-CimInstance Win32_NetworkAdapterConfiguration | where IPEnabled
[IpAddress]$MyIp = $ActiveNic.IPAddress[0]
[IpAddress]$MyMask = $ActiveNic.IPSubnet[0]
[IpAddress]$NetIp = $MyIp.Address -band $MyMask.Address

Then I need to convert the mask and start counting the 1 which I've already got an answer for below. But are there any better ways that are still easy to understand?


Solution

  • My own take..

    function Get-NetId {
    
      [CmdletBinding()]
      param (
        [Parameter()]
        [IpAddress]
        $IpAddress,
    
        [Parameter()]
        [IpAddress]
        $IpMask
      )
    
      [IpAddress]$NetIp = $IpAddress.Address -band $IpMask.Address
    
      [Int]$CIDR = (
        (-join (
          $MyMask.ToString().split('.') | 
            foreach {[convert]::ToString($_,2)} #convert each octet to binary
          ) #and join to one string
        ).ToCharArray() | where {$_ -eq '1'} #then only keep '1'
      ).Count
    
      return $NetIp.ToString() + '/' + $CIDR
    }
    
    
    $ActiveNic = Get-CimInstance Win32_NetworkAdapterConfiguration | where IPEnabled
    [IpAddress]$MyIp = $ActiveNic.IPAddress[0]
    [IpAddress]$MyMask = $ActiveNic.IPSubnet[0]
    
    Get-NetId -IpAddress $MyIp -IpMask $MyMask