Dennis
Dennis

Reputation: 1782

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 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?

Upvotes: 1

Views: 1401

Answers (1)

Dennis
Dennis

Reputation: 1782

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

Upvotes: 1

Related Questions