This repository was archived by the owner on Jul 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 132
Expand file tree
/
Copy pathConvert-Subnetmask.ps1
More file actions
100 lines (81 loc) · 3.03 KB
/
Convert-Subnetmask.ps1
File metadata and controls
100 lines (81 loc) · 3.03 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
###############################################################################################################
# Language : PowerShell 4.0
# Filename : Convert-Subnetmask.ps1
# Autor : BornToBeRoot (https://github.com/BornToBeRoot)
# Description : Convert a subnetmask to CIDR and vise versa
# Repository : https://github.com/BornToBeRoot/PowerShell
###############################################################################################################
<#
.SYNOPSIS
Convert a subnetmask to CIDR and vise versa
.DESCRIPTION
Convert a subnetmask like 255.255.255 to CIDR (/24) and vise versa.
.EXAMPLE
Convert-Subnetmask -CIDR 24
Mask CIDR
---- ----
255.255.255.0 24
.EXAMPLE
Convert-Subnetmask -Mask 255.255.0.0
Mask CIDR
---- ----
255.255.0.0 16
.LINK
https://github.com/BornToBeRoot/PowerShell/blob/master/Documentation/Function/Convert-Subnetmask.README.md
#>
function Convert-Subnetmask
{
[CmdLetBinding(DefaultParameterSetName='CIDR')]
param(
[Parameter(
ParameterSetName='CIDR',
Position=0,
Mandatory=$true,
HelpMessage='CIDR like /24 without "/"')]
[ValidateRange(0,32)]
[Int32]$CIDR,
[Parameter(
ParameterSetName='Mask',
Position=0,
Mandatory=$true,
HelpMessage='Subnetmask like 255.255.255.0')]
[ValidateScript({
if($_ -match "^(254|252|248|240|224|192|128).0.0.0$|^255.(254|252|248|240|224|192|128|0).0.0$|^255.255.(254|252|248|240|224|192|128|0).0$|^255.255.255.(255|254|252|248|240|224|192|128|0)$")
{
return $true
}
else
{
throw "Enter a valid subnetmask (like 255.255.255.0)!"
}
})]
[String]$Mask
)
Begin {
}
Process {
switch($PSCmdlet.ParameterSetName)
{
"CIDR" {
# Make a string of bits (24 to 11111111111111111111111100000000)
$CIDR_Bits = ('1' * $CIDR).PadRight(32, "0")
# Split into groups of 8 bits, convert to Ints, join up into a string
$Octets = $CIDR_Bits -split '(.{8})' -ne ''
$Mask = ($Octets | ForEach-Object -Process {[Convert]::ToInt32($_, 2) }) -join '.'
}
"Mask" {
# Convert the numbers into 8 bit blocks, join them all together, count the 1
$Octets = $Mask.ToString().Split(".") | ForEach-Object -Process {[Convert]::ToString($_, 2)}
$CIDR_Bits = ($Octets -join "").TrimEnd("0")
# Count the "1" (111111111111111111111111 --> /24)
$CIDR = $CIDR_Bits.Length
}
}
[pscustomobject] @{
Mask = $Mask
CIDR = $CIDR
}
}
End {
}
}