Wednesday, January 13, 2021

PowerShell: Write-Output - What does it mean to pass objects along the pipeline

These days I spend a lot of time writing Terraform and PowerShell. There are many blogs about the difference between the various Write-xxx functions in PowerShell, Write-Host, Write-Verbose, Write-ErrorWrite-Output, etc. Many of these posts, such as Writing Output with PowerShellas well as the actual documentation mention that Write-Output passes objects along the pipeline. This has an interesting side effect if you use Write-Output inside of a function in PowerShell. Let's play with some code to see what I mean. 

Let's start with a simple function.


This works as expected, we see the two lines in the output. Now let's make one change when we call the function


One line of the output is missing. This is because Write-Output passes the object along the pipeline. 

What if the function returns something, for example an array of strings? Let's take a look at the code and results in Visual Studio Code. I am hard coding the array here for illustrative purposes, I originally ran into this when I was querying an API and returning results in an array.    



Notice the returned $val, as shown on the left, has three elements in the array. The third is the parameter passed to Write-Output. The type of that is System.Management.Automation.PSObject. 

The challenge I ran into when I found this was that I found the size of the Array in the calling function was larger than the size of the array in the called function. The fact that Write-Output writes objects to the pipeline means we should only be using it when we intend to process the resultant object in a pipeline. If not, I would stay away from Write-Output and choose one of the other variants. If you have a preference of which variant is better and why, I'd love to hear your opinion. 


The 2024 State of DevOps Report and the Importance of Internal Development Platforms

On the State of DevOps Report The State of DevOps Report, published annually by the DevOps Research and Assessment (DORA) team, has been a c...