PowerShell: writing to a file

You might be puzzled that if you use write-host to write to a file to record the session output… it’s empty, thus:

Write-output is what you need, although you do lose those useful colour differences:

Redirect operators achieve the same end:

From a Dos Prompt, you can call PowerShell.exe and wrap and invoke the command:

In fact my own preference is to execute write-host in an ISE window, copy and paste the output into a Word doc or Outlook because that preserves the colour. That applies only if you are not dealing with big volume (you judge what big is).

Oh yeah, sorry, why this difference in behaviour? Because in essence, Write-Host terminates the pipeline, and Write-Output carries it forward to the next action. See Jeffrey Snover’s post here. The point is: be aware that Write-Host is largely considered bad practice… I’m just a sucker for its easy colour highlighting. Perhaps there are other ways to achieve that goal that simply, but I don’t know them.

Leave a comment