Advertisement
atheos42

IPRange-ToArray

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