Skip to content

Instantly share code, notes, and snippets.

@elonmallin
Last active November 7, 2022 09:27
Show Gist options
  • Save elonmallin/8a5e0dfc05d26c2c73a3eb9fda0bfd04 to your computer and use it in GitHub Desktop.
Save elonmallin/8a5e0dfc05d26c2c73a3eb9fda0bfd04 to your computer and use it in GitHub Desktop.
Powershell script to group consecutive numbers
function Group-ConsecutiveNumbers {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline, Mandatory, Position=0)]
$number
)
begin { $numbers = @() }
process { $numbers += $number }
end {
return $numbers |
Select-Object -Unique |
Sort-Object |
ForEach-Object { $g = @() } { if ($g[-1].e -eq ($_ - 1)) { $g[-1].e = $_ } else { $g += @{b=$_;e=$_} } } { $g } |
ForEach-Object { if ($_.b -eq $_.e) { $_.b } else { "$($_.b)..$($_.e)" } }
}
}
# Import:
# Invoke-Expression (iwr "https://gist.githubusercontent.com/elonmallin/8a5e0dfc05d26c2c73a3eb9fda0bfd04/raw/Group-ConsecutiveNumbers.ps1").Content
# Use:
# 1..10 + 12 + 12 + 12 + 14 + 15 + 20..50 + 40 + 80 | Group-ConsecutiveNumbers
# Output:
# 1..10
# 12
# 14..15
# 20..50
# 80
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment