jcgam69
jcgam69

Reputation: 11

In Powershell what is the most efficient way to generate a range interval?

Here is one example, but there must be a more efficient way:

1..100|%{$temp=$_;$temp%=3;if ($temp -eq 0){$_} }

Upvotes: 1

Views: 398

Answers (2)

zdan
zdan

Reputation: 29480

I would guess that the "most efficient" way would be to use a plain old for loop:

for($i=3; $i -le 100; $i +=3){$i}

Though that's not very elegant. You could create a function:

function range($start,$end,$interval) {for($i=$start; $i -le $end; $i +=$interval){$i}}

Timing this against your method (using more pithy version of other answer):

# ~> measure-command {1..100 | Where-Object {$_ % 3 -eq 0}}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 7
Ticks             : 76020
TotalDays         : 8.79861111111111E-08
TotalHours        : 2.11166666666667E-06
TotalMinutes      : 0.0001267
TotalSeconds      : 0.007602
TotalMilliseconds : 7.602

# ~> measure-command{range 3 100 3}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 0
Ticks             : 6197
TotalDays         : 7.1724537037037E-09
TotalHours        : 1.72138888888889E-07
TotalMinutes      : 1.03283333333333E-05
TotalSeconds      : 0.0006197
TotalMilliseconds : 0.6197

Upvotes: 1

Doug Finke
Doug Finke

Reputation: 6823

1..100 | Where-Object {$_ % 3 -eq 0}

Upvotes: 4

Related Questions