1

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

1..100|%{$temp=$_;$temp%=3;if ($temp -eq 0){$_} }
jcgam69
  • 11
  • 1
  • Whatever the answer to the specific statement, to improve the efficiency of a process, you should look to your `whole solution` as **the performance of a complete (PowerShell) solution is supposed to be better than the sum of its parts**, see also: [Fastest Way to get a uniquely index item from the property of an array](https://stackoverflow.com/a/59437162/1701026) – iRon Mar 16 '20 at 11:20

2 Answers2

3
1..100 | Where-Object {$_ % 3 -eq 0}
Doug Finke
  • 6,675
  • 1
  • 31
  • 47
1

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
zdan
  • 28,667
  • 7
  • 60
  • 71
  • Yup, I took efficient to mean a balance of human and machine. I blogged about for loop timings here. http://www.dougfinke.com/blog/index.php/2009/02/20/powershell-four-for-loops-and-their-timings/ – Doug Finke Oct 29 '13 at 21:20