PowerShell Range Operator

Image Description

Daily PowerShell #35

Daily PowerShell Scripting Basics

November 20, 2021

quote Discuss this Article

In this post, we’ll learn about the PowerShell range operator.

What is the PowerShell Range operator?

The PowerShell range operator allows you to generate a series of integers between two values, inclusive.

For example, to create an array of integers from 1 to 100, you could do the following.

1..100

This would print all the integers to the command line after executing the command. You can also create ranges that are reversed by having the larger number on the left.

100..1

Range operators also have some neat tricks.

Hexadecimal Values

Iterate between hexadecimal values.

1..0x05

Scientific Notation

Iterate with numbers using scientific notation.

1..1e6

Storage Sizes

Iterate between storage sizes.

1kb..1mb

What do you use the PowerShell range operator for?

The range operator is useful for several scenarios. We’ll go through some of them below.

Iterating a Number of Times

I use it most often to iterate a set number of times. This is a good replacement for a standard for loop.

With a typical for loop, you would need to define the entire for loop structure.

$Items = for($i = 0; i -lt 100; i++) {
    [object]::new()
}

With the range operator, the syntax is much shorter.

$Items = 1..100 | ForEach-Object {
    [object]::new()
}

I often find this useful when creating sets of test objects. I can use each value of $_ in the ForEach-Object to make it unique.

Selecting a Subset of an Array

You can also use the range operator to select a range of indices within an array. For example, I could have a list of services but only wanted to select the first 50. Remember that arrays in .NET start with 0.

$Services = Get-Service
$Services[0..49]

Generating a Set of Characters

Character encoding sets use numbers to define which bytes map to which characters. Because of this, you can easily use range operators to generate a set of characters.

This example returns the uppercase alphabet.

[char]'A'..[char]'Z'