PowerShell with a Purpose Blog

Making a Debug Log

Got a great question from an attendee at last week's Windows Connections conference. We were discussing how to use the Write-Debug cmdlet to produce "traces" from a script, and one attendee asked if that debug output could be redirected to a file. That way, when he was running a script unattended - as a scheduled task, for example - he could still capture that output. Unfortunately, Write-Debug can't be redirected when it's running in the normal PowerShell console (a custom host could do so, but that was a bit out of scope for this fellow since a custom host requires quite a bit of .NET development).

I suggested instead that he create a replacement for Write-Debug, such as a Write-DebugLog function. Here's what it might look like:

$DebuglogPreference = 'Continue'
function Write-DebugLog {
    [string]$filepath = 'c:\debug.txt'
  if ($DebuglogPreference -eq 'Continue') {
    $message | Out-File $filepath -append

This defines a script-level $DebuglogPreference variable, which when set to 'Continue' will enable logging, and when set to anything else will turn off logging. You call the function like this:

Write-DebugLog 'This is my message'

By default, messages go to a file named c:\debug.txt, although you could pass an alternate filename as a second parameter when calling the function.
Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.