header image

A couple of PowerShell thoughts

Posted by: | April 28, 2010 | 1 Comment |

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

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.

under: PowerShellV2

1 Comment

  1. By: Mike Shepard on August 25, 2010 at 12:41 pm      

    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.