Skip to content

Instantly share code, notes, and snippets.

@MSAdministrator
Created May 24, 2017 02:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MSAdministrator/223292816b26bd71cb273bc74cab8fc2 to your computer and use it in GitHub Desktop.
Save MSAdministrator/223292816b26bd71cb273bc74cab8fc2 to your computer and use it in GitHub Desktop.
Expand-IPRange
<#
.Synopsis
A PowerShell function to expand IP Ranges with dashes
.DESCRIPTION
This function will take an array of IP address ranges and
split them out into single IP addresses
.EXAMPLE
Expand-IPRange -Range '192.0.0.1-192.0.0.100','192.0.0.150-192.0.10.1'
.EXAMPLE
Expand-IPRange -Range '192.0.0.1-192.0.0.100','192.0.0.140','172.0.0.1-172.0.1.240'
#>
function Expand-IPRange
{
[CmdletBinding()]
[Alias()]
[OutputType([int])]
Param
(
# Param1 help description
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$Range
)
Begin
{
$ReturnObject = @()
}
Process
{
foreach ($ipaddress in $($Range))
{
if ($ipaddress -match "-")
{
$splitip = $ipaddress -split '[\-]'
for ($ip=0;$ip -lt $splitip.count;$ip++)
{
if ($ip -eq "0")
{
$startSplitIp = $splitip[$ip]
}
else
{
$endSplitIp = $splitip[$ip]
$ip1 = ([System.Net.IPAddress]$startSplitIp).GetAddressBytes()
[Array]::Reverse($ip1)
$ip1 = ([System.Net.IPAddress]($ip1 -join '.')).Address
$ip2 = ([System.Net.IPAddress]$endSplitIp).GetAddressBytes()
[Array]::Reverse($ip2)
$ip2 = ([System.Net.IPAddress]($ip2 -join '.')).Address
for ($x=$ip1; $x -le $ip2; $x++)
{
$ips = ([System.Net.IPAddress]$x).GetAddressBytes()
[Array]::Reverse($ips)
$ReturnObject += $ips -join '.'
}
}
}
}
else
{
$ReturnObject += $ipaddress
}
}
}
End
{
return $ReturnObject
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment