I’ve recently watched the Powershell jumpstart series and I’m getting dangerous. I have a fairly simple script but I have a feeling there’s an easier (more elegant?) way to do this.
My script creates new deployments in a vmware environment and I want a nicely formatted log in a text file for now. The purpose is so the admin running it can see exactly what was done and also for auditing purpose.
My question is putting the out-file $filename -append and the end of just about every line seems a little crazy. Is Start-Transcript a better option? I did see a forum post about Start-Transcript but it didnt to quite apply to my situation.
Maybe, maybe not. Only the console host supports transcripts, so your script would have to be running in it (e.g., not the ISE or another host). Most folks will create a “logging” function to make this a bit neater. Then you just do something like “Write-Log ‘whatever’” and it takes care of outing to the file.
For simple stuff, I don’t worry about putting logging code in the script itself. I just redirect the script’s output to a file and review it later. For example, in a scheduled task, I might launch:
The “*>” operator is available in PowerShell 3.0 and later; it redirects all streams (output, error, warning, verbose and debug) to the same file.
This approach has a couple of limitations. You don’t get to see the output at the console as the script is running; you have to view it in the log file afterward. I also like to have timestamps in my log files. For that reason, I wrote a module to intercept Host output and redirect it to a file, which you can see here, if you’re interested. It works a lot like Start-Transcript, but works with both the ISE and PowerShell.exe hosts (and very possibly with other custom hosts as well, though I haven’t tested it with anything else.) You can also have multiple captures going at once (with different combinations of streams, if desired), whereas there can only be one Start-Transcript active per session.