4

I have a PowerShell script that outputs to stdout and stderr. I'd like to tee those to a couple log files at the same time.

What's the best way to do this?

A couple things I've considered:

  • Wrap write-error and write-output with a function that does the tee.
    • I don't like this much because (a) I lose my easy ability to just put a value on a line and have it automatically output and (b) I'd have to wrap every place that I'm calling something, including native exe's, that may have output and wrap those as well.
  • Wrap in an outer script that does the tee.
    • This is a little better but now I have the issue of needing to duplicate the param() block from the inner script in the outer script. I could move the param() block entirely but I also want to call the inner script sometimes for testing purposes (i.e. not get the tee). I suppose I could make that an optional behavior in the outer script..

I remember back when I used to write some perl there was a convenient way to redirect all stdout/err output globally, via a hook. Is something like this possible with PowerShell?

1 Answer 1

5

Whoops. I should have spent just a couple more minutes with the Googles.

Start-Transcript does this!

http://technet.microsoft.com/en-us/library/dd347721.aspx

..though it does not capture output of exe's, only PowerShell. Here's a good workaround:

https://web.archive.org/web/20111106093956/blog.magenic.com/blogs/daniels/archive/2008/07/14/Output-Issue-with-Transcript-in-Powershell.aspx

Another update: I discovered that Start-Transcript uses the host window buffer width, which is way too narrow when running a scheduled task on the system account or whatever. Here's how to fix that. Add something like this to the top of the script:

try
{
    $host.ui.rawui.buffersize = `
        new-object system.management.automation.host.size `
            200, $host.ui.rawui.buffersize.height
}
catch {}

Change the 200 to whatever width you want for the transcript.

Sign up to request clarification or add additional context in comments.

1 Comment

There's also nivot.org/2009/08/19/… ... oh, and mark your answer as the answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.