As you know, things aren’t always what they seem in WindowsPowerShell. Take this short script:
The output of the first part is what you’d expect:
All three of the command shown produce output. Fine.However, the second part calls function TestFunc, and produces the followingoutput:
Here, both Out-Host and Write-Host are actually spitting outtext to the console. This occurred when thefunction ran; this “Part 2” output wasn’t part ofthe function’s actual return value. When you look at what was
You can see that anything within a function which is just “output”(that is, without using a cmdlet) becomes concatenated to the function’stotal return. This is in addition to anything explicitly returned using theReturn keyword.
So you have to be careful in how you produce output. Withina script, it’s nearly always safer to produce output by using an outputcmdlet, because within a function any other means won’t produce
That is, not using a cmdlet, is a bad practice (for me, atleast), because it can create inconsistent results depending on where that codeactually occurs. This leaves the question: What’s the difference betweenOut-Host and Write-Host? I know Write-Host doesn’t work properly when you’rehosting PowerShell within another application: Anything produced by Write-Hostproduces a “function not defined” (or some such) error which Ihaven’t wrapped my head around yet. Perhaps perusing the SDK in moredetail will reveal the subtleties there. Stay tuned!