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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s