Archives

I swear I'm going to go on a coordinated campaign against Write-Host. We'll get the government to declare it addictive and harmful, get Microsoft (who created it, after all) to kick in money for anti-Write-Host campaigns, and make people who use it stand outside in the cold with their laptops. Heh.

One of the biggest places I see people using Write-Host these days is to produce what I call "warm and fuzzy" output. That is, little messages like, "Connecting to computer" or "testing for file" that let you know the script is working.

I've got a better way. First, remember, when you use Write-Host, you're producing pure text, and God kills a puppy. So be kind to puppies, and put this at the very tippy-top of your script, after any comment-based help and before any param() block:

[CmdletBinding()]

That turns on some PowerShell superpowers. Next, put your warm and fuzzy into Write-Verbose - and use double quotes, so that you can pop variables in there, rather than concatenating strings. I hate concatenating strings, and I'm pretty sure the puppies do as well.

Write-Verbose "Now connecting to $computername"

Write-Verbose "Testing for file at $filename"

Write-Verbose "The name of the first process is $($processes[0].name)"

Now just run your script normally, adding the -verbose parameter when you want warm/fuzzy, and leaving it off when you don't:

.\Get-Awesomeness -verbose

By using Write-Verbose, you can show or suppress that output whenever you like. Alternate PowerShell hosts (which are going to become more prevalent in the coming years) can capture Verbose output into a log file or something (think something like SCOM or Orchestrator), whereas Host output is a lot trickier to capture.