Select as many ips as possible inside 255 characters string

by Grzegorz Kulikowski

Imagine you have a lot of ips in array, but you want to divide them per 255 characters slices.  We join all them using a comma, and them replace comma by a semicolon

$ip4=1..30 | ForEach-Object { “192.168.1.$_” }
$ip4 -join ‘,’,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

$ip4 -join ‘,’ -replace ‘(\G.{216,255}),’,’$1;’,,,,,,,,,,,,,,,,,,,;,,,,,,,,,
$ip4 -join ‘,’ -replace ‘(\G.{216,255}),’,’$1;’ -split ‘;’ |%{‘Next result’;$_}Next result,,,,,,,,,,,,,,,,,,,
Next result,,,,,,,,,

We are aiming for the commas

We will replace a comma with our first group from the match and put a semicolon. Then we will be splitting strings on semicolons  since we know that at position of the semicolon was the position that could hold the maximum amount of ips in 255 char string area.

And let’s say we are interested only first two batches in case we got more than 30 ips
$ip4 -join ‘,’ -replace ‘(\G.{216,255}),’,’$1;’ -split ‘;’,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

$first,$second,$null = $ip4 -join ‘,’ -replace ‘(\G.{216,255}),’,’$1;’ -split ‘;’

Puts first batch to $first, second batch to $second and the rest goes to null.
This will work also with ipv6, the replace part of regex is greedy, so in case you will be working with ip6 and later with ip4, it will still find the maximum amount of ips. that’s why it has 216-255 instead of 240-255


Function Get-IPsFromString {
Returns chunks of ips from given string limited to $MaxLength of characters from string
If we have 50 ips separated by commas, this function will retrieve as many batches of
ips as there can fit inside $maxlength of character from give string.
If you have to put in some form which is limited to 255 characters ips this function
will diving the ips between
By default is assumes tring limit of 255 characters and min of MaxLength-39 to handle
ipv4 and ipv6 addresses.
Ips are supposed to come as 1 string separated by commas like so:,, etc..
Generate 20 ips and group ips in batches of maximum 60 chars per batch.
PS C:\> (1..20 |%{"192.168.1.$_"}) -join ',' | Get-IPsFromString -MaxLength 60,,,,,,,,,,,,,,,
Kudos to Chris Dent for helping me out with this.
param (
[Parameter(Mandatory,ValueFromPipeline = $True)]
$IPs -join , -replace "(\G.{$($Maxlength39),$MaxLength}),",$1; -split ;

You may also like

Leave a Reply

Chinese (Simplified)EnglishFrenchGermanHindiPolishSpanish