What To Do / Not to Do in PowerShell: Part 12

Reach into your mind, and find the part that knows about the Write-Host cmdlet.

Now, delete that part.

Write-Host is usable only for outputting information directly to the screen, not the pipeline. Data written to the screen can't be exported to XML or CSV, can't be converted to HTML, can't be formatted in different ways - in other words, it's useless.

I'm not trying to get up in your religion or anything, but if you use Write-Host... well, odds are your soul is in jeopardy.

The correct way to output information from a PowerShell cmdlet or function is to create an object that contains your data, and then to write that object to the pipeline by using Write-Output.

For example, let's say you've collected five piece of information into some variables, named $x1, $x2, $x3, $x4, and $x5. You're already in enough trouble for using such horrible, generic variable names; don't compound the problem by writing them to the screen using Write-Host!

$info = {
  'Computername'=$x1;
  'OSVersion'=$x2;
  'Whatever'=$x3;
  'ThisInfo'=$x4;
  'ThatInfo'=$x5
}
Write-Output (New-Object -Type PSObject -Prop $info)

That's how you do it. And resist the urge to format any of that data. If something is in bytes, leave it in bytes at this stage. It's easy enough to format it into gigabytes if that's the goal. For example, suppose your function - the one that contained the above code - was named Get-Stuff. "ThisInfo" contains information in bytes, and for right now you want it in GB. 

Get-Stuff | Format-Table ComputerName,OSVersion,Whatever,@{n='ThisInfo(GB)';e={$_.ThisInfo / 1 GB};
 FormatString="N0"},ThatInfo

See? In your actual function, don't make any permanent decisions about what the output should look like. Save that for a subsequent pipeline step, since the look you need today may not be the look you need tomorrow.

Output objects. Only. Always. Ever.

Discuss this Blog Entry 1

on Aug 11, 2011
Don, I think you are missing a @ in your example

Please or Register to post comments.

What's PowerShell with a Purpose Blog?

Don Jones demystifies Windows PowerShell.

Blog Archive

Sponsored Introduction Continue on to (or wait seconds) ×