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:
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:
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.