Funky times with Write-Host and Out-Host

As you know, things aren’t always what they seem in WindowsPowerShell. Take this short script:

 

"PART 1 ————"

"Hello1"

out-host -input "Hello2"

write-host "Hello3"

 

Function TestFunc {

  "Function1"

  Out-Host -input"Function2"

  Write-Host "Function3"

  Return "Function4"

}

 

"PART 2 ————"

$out = TestFunc

 

"PART 3 ————"

$out

 

The output of the first part is what you’d expect:

 

PART 1 ————

Hello1

Hello2

Hello3

 

All three of the command shown produce output. Fine.However, the second part calls function TestFunc, and produces the followingoutput:

 

PART 2 ————

Function2

Function3

 

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 returned by the function:

 

PART 3 ————

Function1

Function4

 

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 output, it’ll produce return values from the function. I preferto produce all my return values using the Return keyword. In summary, producingoutput like this:

 

“This is output”

 

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!