Logging and tracing information can normally be written to the host console, standard output or standard error streams. However, when a PowerShell script is run from the Windows Task Scheduler, those mechanisms are typically not available.
To work around this situation, I decided to create a log file for my PowerShell Script which is executed from Windows Task Scheduler.
For a start, we can use the .NET StreamWriter class to create a file stream.
1$logFile = New-Object System.IO.StreamWriter("C:\temp\Script.log")
Please note: you must ensure that the user account the script runs under needs to have file system security access to that specific folder and file.
We can then create a function that will write a message to the log file and also flush the stream (I wanted to closely monitor the progress of the script while it may be running, so I am explicitly flushing the stream).
1Function LogMessage($message)
2{
3 $logFile.WriteLine($message)
4
5 $logFile.Flush()
6}
And using the mimicked PowerShell Version 1 Try / Catch / Finally script block, we can ensure that even if an error occurs, the stream will be closed. See the bottom line below.
Here is the script in its entirety.
1# Trap settings
2$ReportErrorShowExceptionClass=$true
3$ReportErrorShowInnerException=$true
4$ReportErrorShowSource=$true
5$ReportErrorShowStackTrace=$true
6
7# Setup log file functionality
8$now=Get-Date
9$logFile = New-Object System.IO.StreamWriter("C:\temp\Script.log")
10
11Function LogMessage($message)
12{
13 $logFile.WriteLine($message)
14 $logFile.Flush()
15}
16
17&{
18 &{ #Try
19 LogMessage("Started at " + $now)
20 ...
21 LogMessage("Successfully finished")
22 }
23 trap #Catch
24 {
25 LogMessage("TRAPPED: " + $_.Exception.GetType().FullName)
26 LogMessage("TRAPPED: " + $_.Exception.Message)
27 continue # So that the "Finally" gets executed
28 }
29} #Finally
30$logFile.Close()
There we have it… a PowerShell script that runs under Windows Task Scheduler and writes out to a log file.
Of course, using the PowerShell Version 2 Try/Catch statement is much nicer than this PowerShell Version 1 equivalent.