Accumulating output objects
In Chapter 7, Reactive Practices – Traditional Debugging, we spent a lot of time discussing replacing the foreach
keyword (loop) with the ForEach-Object
cmdlet. In that section, we were concerned with reading a large amount of data from a file into memory rather than processing it one line at a time. In this section, we will consider the converse, that is, functions that accumulate the objects they are going to output in a container such as an array.
The pipeline is a very powerful and unique feature of the PowerShell language. Executing the cmdlets in the pipeline at the same time as input is available to them, instead of running them sequentially, allows PowerShell scripts to deal with huge amounts of data without incurring a heavy memory footprint. However, we need to be careful if we are going to take advantage of this. Consider the following somewhat contrived function to retrieve the list of services running on a list of computers:
function get-RunningServices...