Ironman Software Forums
Continue the conversion on the Ironman Software forums. Chat with over 1000 users about PowerShell, PowerShell Universal, and PowerShell Pro Tools.
In this post, we’ll learn about 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.
Iterate between hexadecimal values.
1..0x05
Iterate with numbers using scientific notation.
1..1e6
Iterate between storage sizes.
1kb..1mb
The range operator is useful for several scenarios. We’ll go through some of them below.
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.
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]
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'
Find this useful? Please consider sharing this article. Have a question about PowerShell? Contact us and we'll write a post about it.
Continue the conversion on the Ironman Software forums. Chat with over 1000 users about PowerShell, PowerShell Universal, and PowerShell Pro Tools.
Receive once-a-month updates about Ironman Software. You'll learn about our product updates and blogs related to PowerShell.