The Big Book of PowerShell Gotchas
  • ReadMe
  • About this Book
  • Format Right
  • Where is the __ command?
  • PowerShell.exe isn't PowerShell
  • Accumulating Output in a Function
  • ForEach vs ForEach vs ForEach
  • Tab Complete!
  • -Contains isn't -Like
  • You Can't Have What You Don't Have
  • Filter Values Diversity
  • Not Everything Produces Output
  • One HTML Page at a Time, Please
  • Bloody. Awful. Punctuation.
  • Don't Concatenate Strings
  • $ Isn't Part of the Variable Name
  • Use the Pipeline, Not an Array
  • Backtick, Grave Accent, Escape
  • These Aren't Your Father's Commands
  • A Crowd isn't an Individual
  • Commands' Default Output Can Lie
  • Properties vs. Values
  • Remote Variables
  • New-Object PSObject vs. PSCustomObject
  • Running Something as the "Currently Logged-in User"
  • Commands that Need a User Profile May Fail When Run Remotely
  • Writing to SQL Server
  • Getting Folder Sizes
Powered by GitBook
On this page

Accumulating Output in a Function

PreviousPowerShell.exe isn't PowerShellNextForEach vs ForEach vs ForEach

Last updated 7 years ago

This is a bit of an "advanced" gotcha, but it's one that many experienced developers will run into. Here's a very trimmed-down example, just to make the point (it isn't functional, as the command used is fictional):

The problem here is that the function can generate multiple output objects, and the programmer is accumulating those into the $output variable. That means this function won't output anything until it's completely finished running. That isn't how PowerShell commands (and functions are commands) are usually meant to work.

PowerShell commands should usually output each object to the pipeline, one at a time, as those objects are ready. That allows the pipeline to accumulate the output, and to immediately pass it along to whatever is next in the pipeline. That's how PowerShell commands are intended to work. Now, there are always exceptions. Sort-Object, for example, has to accumulate its output, because it can't actually sort anything until it has all of them. So it's called a _blocking command, _because it "blocks" the pipeline from doing anything else until it produces its output. But that's an exception.

It's usually easy to fix this, by simply outputting to the pipeline instead of accumulating:

image009.png
image011.png