But nobody listens to me. And some people don’t even listen to Jeffrey. Write-Host continues to exist in a bazillion old and many new scripts. So the PowerShell team decided to fix it. Or make it less bad.
The problem with Write-Host was that it bypassed the output stream (and all of the other streams), and sent data directly to the “host” to be displayed on the screen. This meant that you couldn’t redirect the result and you couldn’t capture it in a variable. If you moved code whose only output was Write-Host into a function, you found it didn’t work, because only the streams are returned to the calling script. Plus, sometimes code runs in an environment where there is no host, at least not one that can understand what to do with Write-Host, so these scripts just fail.
The PowerShell team introduced a new stream in version 5, named Information, which comes with a Write-Information command (the analog to Write-Output, Write-Verbose, Write-Error, etc.). They decided to leverage this to redesign Write-Host, and rewrote is as a wrapper for Write-Information.
So now in PowerShell 5, Write-Host writes to the Information stream, which by default goes to the host and nowhere else.
There is still almost no reason to ever use Write-Host. It’s pretty useless. Usually writing to the Output stream is preferred or adequate, as it by default writes to the screen as well. And you can do that easily by just outputting something. “Message” does what you thought you were doing with Write-Host “Message”.
And if you do want to write to the Information stream instead of the Output stream, use Write-Information; that’s what it’s for.
The one thing that Write-Host can do that Write-Information can’t, is to write to the screen in pretty colors. Personally, I would prefer to enhance my scripts in other ways, like automatically handling extreme conditions, or using pretty reports where needed, or adding a GUI, or whatever, but if you want to write text to the screen in pretty colors, you now more safely use Write-Host for that.
No comments:
Post a Comment