PowerShell comes with a number of looping constructs. These looping constructs cannot stream, so you cannot pipe the results to other cmdlets and use the pipeline real-time benefits. Instead, you must store all data in variables first, and only when the loop is completed can you pipe the variable to someone else.

While you can resort to ForEach-Object to replace classic foreach and for loops, it slows down code and is no solution for while and do loops.

Here is an easy trick how you can enable fast streaming for any loop. Let’s take this rather stupid loop to play with:

# stupid sample using a do loop
# a more realistic use case could be a database query

do
{
  $val = Get-Random -Minimum 0 -Maximum 10
  $val
  
} while ($val -ne 6)

It loops until the random number 6 is drawn. You’ll see that you cannot pipe the results in real-time, so you have to resort to something like this to sort the results or do other things with them:

$all = do
{
  $val = Get-Random -Minimum 0 -Maximum 10
  $val
  
} while ($val -ne 6)

$all | Out-GridView

By enclosing the loop into a script block, you get real-time streaming: less memory consumption, immediate results:

& { do
{
  $val = Get-Random -Minimum 0 -Maximum 10
  $val
  
} while ($val -ne 6) } | Out-GridView  

psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU - with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!

Anonymous