A couple of PowerShell thoughts

I’ve been looking at a lot of scripts over the last few days and a couple of thoughts occurred while judging.  These have nothing to do with the Scripting Games but are more concerned with PowerShell in general.

Write-Host is used to output to the screen.  That works fine but its not so easy if you want to be able to run the script and output to screen or file.  Consider this

PS> $date = Get-Date
PS> Write-Host "Started at $date"
Started at 04/28/2010 22:54:17

PS>  "Started at $date"
Started at 04/28/2010 22:54:17

We can use write-host to output to screen. We can put the same output by having a line with a string on it – its treated as output.

If we want to write to a file

PS> Write-Host "Started at $date" | out-file test1.txt
Started at 04/28/2010 22:54:17
PS> cat test1.txt
PS>

Write-host will always write to the screen.

PS>  "Started at $date" | out-file test1.txt
PS> cat test1.txt
Started at 04/28/2010 22:54:17

Output via a string can be redirected to a file.

Consider what you are trying to achieve. If you want the comments in a file then done use write-host.

The other thought was around how scripts close.  Very often our pipeline will finish with a format-table (or list).  I try to use a select instead.  That means I can add a simple format-table to the end or can write straight out to file – again think about what is being achieved.

One Response to A couple of PowerShell thoughts

  • Mike Shepard says:

    I agree. I’ve been guilty of mixing the two options you’ve mentions with return statements (in functions) and write-output calls.

    What I’ve settled on is using write-output for human-oriented messages, using return for single function output, and write-output for multiple function output.

Leave a Reply