4

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.

dreftymac
  • 31,404
  • 26
  • 119
  • 182
constructor
  • 1,412
  • 1
  • 17
  • 34

1 Answers1

8

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
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • understand, but my powershell returns error for published sample. Updated code `(1..10) | where ({$_ % 2 -eq 0})` returns correct result – constructor Nov 24 '15 at 11:27
  • @constructor: I guess the capability to call extension methods is new in PowerShell 5. I haven't seen or used it either so far. I also think most PowerShell code should not use LINQ but rather the respective cmdlets. – Joey Nov 24 '15 at 11:29
  • Ahh, you are running PowerShell 2.0? If so, the `Where()` method doesn't exist, but yes, as mentioned, the `Where-Object` cmdlet will work just as well – Mathias R. Jessen Nov 24 '15 at 11:31
  • @Joey The `Where()` extension method was [introduced in PowerShell 4.0](https://technet.microsoft.com/en-us/library/hh857339.aspx#BKMK_core) - it's not LINQ, it's a PS language feature. OP didn't mention which version he was running – Mathias R. Jessen Nov 24 '15 at 11:33
  • 1
    Oh, nice to know. I kinda lost track of the newer language features. – Joey Nov 24 '15 at 11:50
  • I have assuming lowest common denominator for answers lately. I am missing out on newer features as well :( – Matt Nov 24 '15 at 12:54
  • @Matt Unless there's an obvious idiomatic way of doing something, I usually try to present alternatives. `.Where()` operates significantly faster on large collections (no pipeline overhead) – Mathias R. Jessen Nov 24 '15 at 13:04
  • 1
    I wonder why no one commented on the fact this is actually a bit different than what was requested. The steps should be offset from the original position and not from `0`, as is the common interpretation of steps on a range. Should probably update the condition in the answer to be `($_-) % 2 -eq 0` or `1..10 |Where-Object {($_-1) % 2 -eq 0}` in this specific case. – Assaf Israel Dec 21 '17 at 04:50