I’m self-taught with PowerShell and I’ve written a few scripts now, some of which are pretty powerful. Despite this, I worry that I might not be using PowerShell in its intended way. Here are my two main concerns:
-
From what I’ve read, PowerShell scripts should be written in such a way that they can be piped into and also so that they can pipe their output into something else. But the way I wrote my scripts is to be completely stand-alone and output everything to the user via
Write-Host. -
Another thing I’ve read is that when errors come up (for example, you try to read a file but don’t have permission), you should use
Write-Errorrather thanWrite-Host. I don’t do this, though. I just capture the plain English error message and output it withWrite-Hostso it’s more user-friendly for people who don’t know anything about PowerShell or coding other than how to run scripts.
Are either of these things heavily frowned upon in the PowerShell community? If I showed one of my powerful, well-commented, easy-to-read scripts to an advanced PowerShell coder, would he scoff at it and call it garbage?
Some of my scripts could be useful to others, but I hesitate to show the code to anybody for fear that my style isn’t correct. Any help would be appreciated. Thanks!
I don’t think that it is expected of a script to use
write-outputrather thanwrite-hostso that the output can be piped to other scripts etc. Cmdlets and maybe functions can be expected to do that, but not scripts. If you have to display something to the user about the actions that the script is doing, you might as well useWrite-Host. Note that usingWrite-Outputmight be good, if you want to log the output of the script to a logfile AND display on the screen to the user. Doing that when you are usingWrite-Hostcannot be done easily / efficiently.Write-Erroradd some additional info that IMO is not necessary. I rarely useWrite-Error. I useWrite-Host -fore red messageto indicate errors in my scripts. That keeps it nice and simple.But of course, we can’t make statements like always use Write-Output or always use Write-Host etc. It is going to depend on the situation and how you are going to be using the scripts.