Creating IPv4 Network Range

by Mar 20, 2023

Here is a PowerShell code snippet that creates a list of IPv4 addresses for a given segment. You just specify the start and end address:

$From = "192.168.2.12"
$To = "192.168.3.11"

$ipFromBytes = [System.Net.IPAddress]::Parse($From).GetAddressBytes()
$ipToBytes = [System.Net.IPAddress]::Parse($to).GetAddressBytes()

# change endianness (reverse bytes)
[array]::Reverse($ipFromBytes)
[array]::Reverse($ipToBytes)

# convert reversed bytes to uint32
$start=[system.BitConverter]::ToUInt32($ipFromBytes, 0)
$end=[system.BitConverter]::ToUInt32($ipToBytes, 0)

# enumerate from start to end uint32
for($x = $start; $x -le $end; $x++)
{
  # split uit32 back into bytes
  $ip=[bitconverter]::getbytes($x)
  # reverse bytes back to normal
  [Array]::Reverse($ip)
  # output ipv4 address as string
  $ip -join '.'
}

Tweet this Tip! Tweet this Tip!