PowerShell to get the CIDR Notation by Subnet Mask

The following function provides an easy way to get the CIDR (Classless Inter Domain Routing) notation for any subnet mask using PowerShell.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Calculate CIDR (Classless Inter Domain Routing) Notation
function getCIDRNotationBySubnetmask([string]$subnetmask){
 
    $cidr = 0
    $subnetmask.split(".") | foreach {
        switch($_){
            255 { $cidr += 8 }
            254 { $cidr += 7 }
            252 { $cidr += 6 }
            248 { $cidr += 5 }
            240 { $cidr += 4 }
            224 { $cidr += 3 }
            192 { $cidr += 2 }
            128 { $cidr += 1 }
            default { $cidr += 0 }
        }
    }
 
    return $cidr
}
 
# Examples how to use it
getCIDRNotationBySubnetmask 0.0.0.0
 
getCIDRNotationBySubnetmask 128.0.0.0
getCIDRNotationBySubnetmask 192.0.0.0
getCIDRNotationBySubnetmask 224.0.0.0
getCIDRNotationBySubnetmask 240.0.0.0
getCIDRNotationBySubnetmask 248.0.0.0
getCIDRNotationBySubnetmask 252.0.0.0
getCIDRNotationBySubnetmask 254.0.0.0
getCIDRNotationBySubnetmask 255.0.0.0
 
getCIDRNotationBySubnetmask 255.128.0.0
getCIDRNotationBySubnetmask 255.192.0.0
getCIDRNotationBySubnetmask 255.224.0.0
getCIDRNotationBySubnetmask 255.240.0.0
getCIDRNotationBySubnetmask 255.248.0.0
getCIDRNotationBySubnetmask 255.252.0.0
getCIDRNotationBySubnetmask 255.254.0.0
getCIDRNotationBySubnetmask 255.255.0.0
 
getCIDRNotationBySubnetmask 255.255.128.0
getCIDRNotationBySubnetmask 255.255.192.0
getCIDRNotationBySubnetmask 255.255.224.0
getCIDRNotationBySubnetmask 255.255.240.0
getCIDRNotationBySubnetmask 255.255.248.0
getCIDRNotationBySubnetmask 255.255.252.0
getCIDRNotationBySubnetmask 255.255.254.0
getCIDRNotationBySubnetmask 255.255.255.0
 
getCIDRNotationBySubnetmask 255.255.255.128
getCIDRNotationBySubnetmask 255.255.255.192
getCIDRNotationBySubnetmask 255.255.255.224
getCIDRNotationBySubnetmask 255.255.255.240
getCIDRNotationBySubnetmask 255.255.255.248
getCIDRNotationBySubnetmask 255.255.255.252
getCIDRNotationBySubnetmask 255.255.255.254
 
getCIDRNotationBySubnetmask 255.255.255.255

Leave a Reply

Your email address will not be published. Required fields are marked *