PowerShell Write Commands how we managed to misuse them for a long time, and the pain when we fixed their usage
TL;DR As the PowerShell Write commands do not use consistent parameters swapping the command between Write-Information and Write-Verbose can easily go wrong. This is a good thing as they are not meant to be interchangeable.
Quick one this week but as we migrate people at different organisations into Azure Landing Zones we are revisiting a lot of PowerShell scripts.
One thing we found was that the use of the PowerShell Write commands, e.g. Write-Host, Write-Information, Write-Verbose, Write-Error, Write-Output was pretty inconsistent in their usage so we started tidying them up so that each had a definite purpose. We used Write-Information for things that may be of interest if monitoring a script but should not necessarily end up on the Standard Out stream, in case that is being used, which its not designed to do. We used Write-Verbose for information that is only of interest if a script is being run to debug it in a non-interactive environment, e.g. an Azure DEVOps multi-stage pipeline, which is the job of Write-Debug.
So we read the documentation and started using them for their correct purposes.
Scripts started failing.
We tracked it back to the inconsistency of the Write commands parameters. Most use Message, but one uses MessageData, one uses InputData, one Object, etc. So as we update the command, say from Write-Verbose to Write-Debug we didn’t change the parameters.
This is good because they are not some sort of logging levels but designed to do different things.
If your interested here is what we use the common Write commands for
- Write-Debug: writing debug information out, typically in a non-interactive environment. Uses -Message.
- Write-Error: writing non-terminating error information. Uses -Message.
- Write-Host: communicating with host via standard out stream. Uses -Object
- Write-Information: communicating with host via standard out stream. Uses -MessageData.
- Write-Output: Used to write the specified objects to the pipeline. If Write-Output is the last command in the pipeline, the objects are displayed in the console. Uses -InputData.
- Write-Progress: Used to display a status bar. Uses -Status.
- Write-Verbose: Used to add additional text to the output stream, a seperate verbose stream on windows. Uses -Message.
- Write-Warning: Used to output warnings on the error stream, which unix based systems interpret as errors. Uses -Message.
TL;CR As the PowerShell Write commands do not use consistent parameters swapping the command between Write-Information and Write-Verbose can easily go wrong. This is a good thing as they are not meant to be interchangeable.