"repeat" and "slowly" filters

Topics: Developer Forum
Mar 23, 2007 at 1:02 AM
Jeff Snover (MSFT) posted the following filter on his blog:

> filter slowly ($tempo=100) { $_; Start-Sleep -milliseconds $tempo}


That got me thinking and so I right away created another useful filter:

> filter repeat ($count=-1) { if($count -eq -1) { while(1) { $_ } } else { while($count) { $_; $count=$count-1 } } }


Try composing them together, as in:

> gps MyApp | select handles | repeat | slowly 1000
Mar 23, 2007 at 1:02 AM
http://blogs.msdn.com/powershell/archive/2007/03/04/slowing-output.aspx
Mar 30, 2007 at 3:32 AM
Trying this alongside taskmgr, it seems clear that this approach always gets you the same value as whatever came into repeat, so I'm not sure what the benefit is.

I think you'd want something like this instead:

filter repeat (scriptblock $block, int $count=-1) { if($count -eq -1) { while(1) { & $block } } else { while($count) { & $block; $count=$count-1 } } }

Your example then becomes:

repeat { gps iexplore | select handles } | slowly 1000

Not quite as nice in syntax, but it seems to have the intended effect.
Apr 12, 2007 at 10:41 PM
Edited Apr 12, 2007 at 10:50 PM
Yup, I discovered that a few days ago. However, even the one above needs a bit of work so that $block can impact the current scope. Oh, and I don't think writing it as a filter is the right idea anymore; in fact, I think it should be a function instead, because I don't understand how it would meaningfully interact with the object pipe (does not seem to do anything).

With your version:
$x = 0; repeat { $x++; $x } 3; $x

produces:
1
1
1
0

So, use a "." to execute $block in the containing scope instead (and switch to a function):

function repeat( scriptblock$block, int$count=-1 ) {
if($count -ne -1) {
while( $count-- -gt 0 ) {
. $block
}
}
else {
while($true) {
. $block }
}
}

Now, the following:
$x=0; repeat { $x++; $x } 3; $x

Produces:
1
2
3
0

And:
$x=0; . repeat { $x++; $x } 3; $x

Gives:
1
2
3
3