Convention for returning object output

by MattG at 2012-08-19 11:35:53

What is the generally accepted best practice for returning objects - Write-Object $SomeObject or just $SomeObject?

Write-Output is clearer to someone reading your code than just emitting the object, in my opinion. However, what do you experts prefer / consider to be best practice? And yes, I do realize I’m being fastidious. ;D
by DonJ at 2012-08-19 11:41:33
Write-Output, mainly because - as you noted - it’s more readable. It’s good to be fastidious this way ;).
by MattG at 2012-08-19 11:43:58
Cool. Thanks, Don.
by poshoholic at 2012-08-19 11:47:40
Personally I never use Write-Output. While Write-Output might be clearer to someone else reading your script, it isn’t guaranteed to identify all of the places where something is returned from the script and therefore may be misleading as well, depending on whether or not you’ve done your due diligence to make sure Write-Output is everywhere it needs to be. This can be harder when working with multiple authors of a script as well. On the flipside, you’re not misleading anyone when you don’t use Write-Output-- the command simply outputs what it lets fall through.

My recommendation is to use #region statements to identify blocks of business logic, describing what each part of a script does. Modern editors support regions (even PowerShell ISE in version 3), and being able to see a script described in a few single sentences of business logic makes all the difference in the world when it comes to someone else reading your script. I use regions to identify when I return something back to the caller as well.

Also, when it comes to output, don’t forget the OutputType attribute. This identifies the types of objects your script or function is designed to return, which goes a long way when reading the script because you know what to look for right from the start.
by MattG at 2012-08-19 12:08:00
Awesome recommendations. Thanks, Kirk.