Lessons In PowerShell - Logging From A Script Running Via Windows Task Scheduler

   Submit to Reddit      
  

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.

$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).

Function LogMessage($message)
{
    $logFile.WriteLine($message)

    $logFile.Flush()
}

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.

# Trap settings
$ReportErrorShowExceptionClass=$true
$ReportErrorShowInnerException=$true
$ReportErrorShowSource=$true
$ReportErrorShowStackTrace=$true

# Setup log file functionality
$now=Get-Date
$logFile = New-Object System.IO.StreamWriter("C:\temp\Script.log")

Function LogMessage($message)
{
    $logFile.WriteLine($message)
    $logFile.Flush()
}

&{
    &{ #Try 
          LogMessage("Started at " + $now)
          ...
          LogMessage("Successfully finished")
    } 
    trap #Catch
    {
        LogMessage("TRAPPED: " + $_.Exception.GetType().FullName) 
        LogMessage("TRAPPED: " + $_.Exception.Message)
        continue # So that the "Finally" gets executed
    }
} #Finally
$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.



comments powered by Disqus