PowerShell Error Log File

PowerShell is great for scheduling administrative tasks, but it can be difficult to figure out a reliable way to log the error output if things go wrong. The Windows task scheduler will record last run result of 0x1 (error), but no text log (assuming $ErrorActionPreference = "Stop"). If you’re using the older cmd.exe scripts, you can usually use >logfile.txt 2>&1, but this is not reliable in PowerShell to capture all errors. One native logging capability that you may want to try is the “transcript” feature. Just add Start-Transcript to the beginning of your script, and Stop-Transcript to the end. If you’re running PowerShell 5.0 (check with $host.version), you can also customize the output folder using the -OutputDirectory option of Start-Transcript. If you’re running POWERSHELL OLDER THAN 5.0, you can still use a custom log directory, but you must also specify the transcript log file name. Here’s a sample compatible with PowerShell 2.0.

$ErrorActionPreference = "Stop"
$logDir = "C:\Users\yourUserName\Documents"
$timeStamp = Get-Date -Format "yyyyMMddHHmm"
$logFile = "PowerShell_transcript_$($timeStamp).txt"
Start-Transcript (Join-Path $logDir $logFile)
# In PowerShell 5.0 and newer, you can use the shorter: 
#   Start-Transcript -OutputDirectory $logDir

You may also want to schedule another script to delete old log files or zip them up to keep the log output folder clean. This example assumes a typical user Documents folder, but you will likely want to create a special directory just for these transcripts.


About notesbytom

Keeping technology notes on WordPress.com to free up my mind to solve new problems rather than figuring out the same ones repeatedly :-).
This entry was posted in System Administration and tagged , , . Bookmark the permalink.

3 Responses to PowerShell Error Log File

  1. Great tip! You can also use -Path and -Append

    Start-Transcript -path C:\output.txt -append
    # Commands here:

  2. notesbytom says:

    Hello Michael, yes -Path is the argument used (implied) in my example here. The point I was making is that -Path appears to require the full directory + file-name. I like the new PS 5.0 feature where we can specify a log folder only and let PowerShell automatically generate the unique log file names. Of course if we provide no parameters at all, the transcript will still be created (in the PowerShell default location). Glad to see others are using the same transcript features :-).

  3. Pingback: Task Scheduler PowerShell Script Log File | Notes by Tom

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s