PowerShell range operator for other types

Thu, Sep 7, 2006 One-minute read

The PowerShell range operator allows you to generate lists of numbers out of more compact expressions:

PS >1..5
1
2
3
4
5

PS >6..4
6
5
4

Something that came up on the newsgroup was the desire for range operators on data types other than the numeric ones.  It’s a feature we wanted to add, but weren’t able to.  In the meantime, this script / function accomplishes the goal quite well:

PS >range Friday Monday DayOfWeek
Friday
Thursday
Wednesday
Tuesday
Monday

PS >range y v char
y
x
w
v

And the script:

## Range.ps1
## Support ranges on variable types other than numeric
## 
## range Stop Inquire System.Management.Automation.ActionPreference
## range Friday Monday DayOfWeek
## range c q char
param([string] $first, [string] $second, [string] $type)

$rangeStart = [int] ($first -as $type)
$rangeEnd = [int] ($second -as $type)

$rangeStart..$rangeEnd  | % { $_ -as $type }