PowerShell range operator for other types

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

## Range.ps1
## Support ranges on variable types other than numeric
## 
## range Stop Inquire System.Management.Automation.ActionPreference
## range Friday Monday DayOfWeek
## range e g char

param([string] $first, [string] $second, [string] $type)

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

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

2 Responses to “PowerShell range operator for other types”

  1. Sung Kim writes:

    Is there a way to override that ".." range operator in PowerShell?

    I am wondering if it is possible to change the behavior(or override) range operator depending on the types used in types.ps1xml.

    So suppose that, if I am to override ".."’s behavior for the type "System.Management.Automation.ActionPreference",
    "Stop..Inquire" (without quotes) would generate
    Stop,Continue,Inquire array.

  2. Lee writes:

    PowerShell doesn’t currently support language extensions. The only option right now is to use the postfix notation (ie: add 5 6, range 1 10 int) that functions and scripts provide.

Leave a Reply