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 # ... YOUR SCRIPT CODE GOES HERE ... Stop-Transcript
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.