Advertisement
atheos42

IPRange-ToList

Sep 14th, 2022 (edited)
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PowerShell 1.88 KB | Source Code | 0 0
  1. using namespace System.Collections.Generic
  2.  
  3. function IPRange-ToList{
  4.     Param ( [Parameter(Mandatory=1,HelpMessage='Starting IP Address',ValueFromPipeline=1)][ipaddress]$Start,
  5.             [Parameter(Mandatory=1,HelpMessage='Ending IP Address'  ,ValueFromPipeline=1)][ipaddress]$End
  6.     )
  7.  
  8.     $s_oct = [PSCustomObject] @{
  9.         a = $Start.GetAddressBytes()[0]
  10.         b = $Start.GetAddressBytes()[1]
  11.         c = $Start.GetAddressBytes()[2]
  12.         d = $Start.GetAddressBytes()[3]
  13.         ab = $Start.GetAddressBytes()[0..1] -join '.'
  14.         abc = $Start.GetAddressBytes()[0..2] -join '.'
  15.     }
  16.  
  17.     $e_oct = [PSCustomObject] @{
  18.         a = $End.GetAddressBytes()[0]
  19.         b = $End.GetAddressBytes()[1]
  20.         c = $End.GetAddressBytes()[2]
  21.         d = $End.GetAddressBytes()[3]
  22.         ab = $End.GetAddressBytes()[0..1] -join '.'
  23.         abc = $End.GetAddressBytes()[0..2] -join '.'
  24.     }
  25.  
  26.     $ip_list = [System.Collections.Generic.List[PSObject]]::new()
  27.  
  28.     # check if there is a difference in the c octets.
  29.     if($s_oct.c -eq $e_oct.c){
  30.         $s_oct.d..$e_oct.d | ForEach-Object { $ip_list.Add($($s_oct.abc + ".$_")) }
  31.     }else{
  32.  
  33.         # add 1st range
  34.         $s_oct.d..255 | ForEach-Object { $ip_list.Add($($s_oct.abc + ".$_")) }
  35.  
  36.         # check if the difference between the c octets is greater than 1
  37.         #if greater, sequencial loop adding ranges
  38.         if([math]::Abs($s_oct.c - $e_oct.c) -gt 1){
  39.             $tmp = $s_oct.c + 1
  40.             while($tmp -lt $e_oct.c){
  41.                 1..255 | ForEach-Object { $ip_list.Add($($s_oct.ab + ".$tmp.$_")) }
  42.                 $tmp += 1
  43.             }
  44.         }
  45.  
  46.         # add last range
  47.         1..$e_oct.d | ForEach-Object { $ip_list.Add($($e_oct.abc + ".$_")) }
  48.     }
  49.     return $ip_list
  50. }
  51.  
  52. Clear-Host
  53. IPRange-ToList '192.168.0.100' '192.168.2.10'
  54.  
  55. IPRange-ToList -Start '10.10.1.1' -End '10.10.2.50'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement