PowerShell Cookbook

Search

Categories

 

On this page

PowerShell range operator for other types

Archive

Blogroll

Disclaimer
I work for Microsoft.

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 214
This Year: 14
This Month: 1
This Week: 0
Comments: 522

Sign In

 Thursday, September 07, 2006
Thursday, September 07, 2006 4:59:38 PM (Pacific Daylight Time, UTC-07:00) ( )

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 }