Building a list of IP addresses Building a list of IP addresses powershell powershell

Building a list of IP addresses


I wrote this using some similar questions to get the first and last address for any subnet given a random IP and mask:

Function Get-SubnetAddresses {Param ([IPAddress]$IP,[ValidateRange(0, 32)][int]$maskbits)  # Convert the mask to type [IPAddress]:  $mask = ([Math]::Pow(2, $MaskBits) - 1) * [Math]::Pow(2, (32 - $MaskBits))  $maskbytes = [BitConverter]::GetBytes([UInt32] $mask)  $DottedMask = [IPAddress]((3..0 | ForEach-Object { [String] $maskbytes[$_] }) -join '.')    # bitwise AND them together, and you've got the subnet ID  $lower = [IPAddress] ( $ip.Address -band $DottedMask.Address )  # We can do a similar operation for the broadcast address  # subnet mask bytes need to be inverted and reversed before adding  $LowerBytes = [BitConverter]::GetBytes([UInt32] $lower.Address)  [IPAddress]$upper = (0..3 | %{$LowerBytes[$_] + ($maskbytes[(3-$_)] -bxor 255)}) -join '.'  # Make an object for use elsewhere  Return [pscustomobject][ordered]@{    Lower=$lower    Upper=$upper  }}

Usage looks like:

Get-IPAddresses 10.43.120.8 22Lower       Upper        -----       -----        10.43.120.0 10.43.123.255

And I put this together to generate the whole list. I'm sure this could be done better, but the simple instructions run fast enough:

Function Get-IPRange {param (  [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName)][IPAddress]$lower,  [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName)][IPAddress]$upper)  # use lists for speed  $IPList = [Collections.ArrayList]::new()  $null = $IPList.Add($lower)  $i = $lower  # increment ip until reaching $upper in range  while ( $i -ne $upper ) {     # IP octet values are built back-to-front, so reverse the octet order    $iBytes = [BitConverter]::GetBytes([UInt32] $i.Address)    [Array]::Reverse($iBytes)    # Then we can +1 the int value and reverse again    $nextBytes = [BitConverter]::GetBytes([UInt32]([bitconverter]::ToUInt32($iBytes,0) +1))    [Array]::Reverse($nextBytes)    # Convert to IP and add to list    $i = [IPAddress]$nextBytes    $null = $IPList.Add($i)  }  return $IPList}

Converting to [IPAddress] on the last line is nice for validating all the results are real, but probably not necessary if you just want the ipv4 strings. Usage:

Get-SubnetAddresses 10.43.120.8 30 | Get-IPRange | Select -ExpandProperty IPAddressToString10.43.120.810.43.120.910.43.120.1010.43.120.11

Sources: