The PowerShell range operator generates a list of values:
>1..6
1
2
3
4
5
6
How can I generate a list of values with a specific step? For example, I need a list from 1 to 10 with step 2.
The PowerShell range operator generates a list of values:
>1..6
1
2
3
4
5
6
How can I generate a list of values with a specific step? For example, I need a list from 1 to 10 with step 2.
The range operator itself doesn't support skipping/stepping, but you could use Where-Object
(or the Where()
method if you're running version 4.0 or above) to filter out every second:
PS C:\> (1..10).Where({$_ % 2 -eq 0})
2
4
6
8
10
Version 2.0 and up:
PS C:\> 1..10 |Where-Object {$_ % 2 -eq 0}
2
4
6
8
10
Where()
method doesn't exist, but yes, as mentioned, the Where-Object
cmdlet will work just as well –
Bili Where()
extension method was introduced in PowerShell 4.0 - it's not LINQ, it's a PS language feature. OP didn't mention which version he was running –
Bili .Where()
operates significantly faster on large collections (no pipeline overhead) –
Bili 0
, as is the common interpretation of steps on a range. Should probably update the condition in the answer to be ($_-<first-element>) % 2 -eq 0
or 1..10 |Where-Object {($_-1) % 2 -eq 0}
in this specific case. –
Stingaree © 2022 - 2024 — McMap. All rights reserved.
(1..10) | where ({$_ % 2 -eq 0})
returns correct result – Imtiaz