Skip to content

Instantly share code, notes, and snippets.

@bwright86
Created September 16, 2019 11:07
Show Gist options
  • Save bwright86/228c7d1c639d465ced63410bebcf30db to your computer and use it in GitHub Desktop.
Save bwright86/228c7d1c639d465ced63410bebcf30db to your computer and use it in GitHub Desktop.
A powershell function to convert a string input of numbers into an array. Handles CSV or ranges.
<#
.Synopsis
Extracts integers from strings, including CSV and ranges.
.DESCRIPTION
A longer description that describes what is being done.
####
# Author: Brent Wright
# Date Created: 09/16/2019
# Date Updated: mm/dd/yyyy
.EXAMPLE
Get-StringNumbers 1234
# Returns: 1234
.EXAMPLE
"123, 456" | Get-StringNumbers
# Returns: @(123, 456)
.EXAMPLE
"10-12" | Get-StringNumbers
# Returns: @(10, 11, 12)
.NOTES
Updates:
mm/dd/yyyy - user.name - fixed a bug, added a new feature...
.COMPONENT
The component this cmdlet belongs to
.ROLE
The role this cmdlet belongs to
.FUNCTIONALITY
The functionality that best describes this cmdlet
#>
function Convert-StringNumbers {
param([parameter(mandatory = $true, ValueFromPipelineByPropertyName)]
[ValidateScript({
if ($_ -match "^(?:\d+)((?:,\s?\d+|-\d+)+)?$") { $true } else {
throw "[$_] is not valid. Valid formats are: [1234], [1234, 1235, ...], [1234-1240]" }
})]
[string]
$InputObject)
process {
$numbers = ($InputObject -split ",").Trim()
"Num count: {0} - {1}" -f $numbers.count, $($numbers -join ", ") | Write-Verbose
foreach ($number in $numbers) {
if ($number -like "*-*") {
$first, $last = $number -split "-"
"Range detected..." | Write-Verbose
($first..$last)
} else {
$number
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment