Q. Should I ever use Write-Host in PowerShell?
A. You should rarely use the Write-Host cmdlet. Write-Host puts content directly on the screen. If that's all you need to do, then you can use it. But here's the problem: Suppose you write a script, and it uses Write-Host to output everything. Let's say that the output consists of information on a computer, like its BIOS serial number and OS version number. Your script might look like this:
$os = gwmi win32_operatingsystem $bios = gwmi win32_bios write-host ($os.buildnumber) write-host ($bios.serialnumber)
The problem with that is you can't repurpose the script output in any way. If your script was named Get-Info.ps1, you couldn't do this:
./Get-Info | Export-CSV info.csv
Why not? Because there's nothing being placed into the pipeline by your script. However, if you constructed a custom object to hold your output, and wrote that to the pipeline, you'd open up a world of possibilities:
$os = gwmi win32_operatingsystem $bios = gwmi win32_bios $obj = new-object psobject $obj | add-member noteproperty OSBuild ($os.buildnumber) $obj | add-member noteproperty BIOSSerial ($bios.serialnumber) write-output $obj
Now, you could pipe the script's output to any other cmdlet, like Export-CSV, Format-Table, and so on. It's a much more flexible way to produce output.
Do you have a Windows PowerShell question? Find more PowerShell FAQs, articles, and other resources at windowsitpro.com/go/DonJonesPowerShell.