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 {
  param(
    [string]$message,
    [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.

Please or Register to post comments.

What's PowerShell with a Purpose Blog?

Don Jones demystifies Windows PowerShell.

Blog Archive

Sponsored Introduction Continue on to (or wait seconds) ×