Redirection of standard and error output appending to the same log file

前端 未结 4 676
孤街浪徒
孤街浪徒 2020-11-30 00:27

I need to collect the standard output and error log from several processes into one single log file.

So every output must append to this log file.

4条回答
  •  旧时难觅i
    2020-11-30 00:49

    Andy gave me some good pointers, but I wanted to do it in an even cleaner way. Not to mention that with the 2>&1 >> method PowerShell complained to me about the log file being accessed by another process, i.e. both stderr and stdout trying to lock the file for access, I guess. So here's how I worked it around.

    First let's generate a nice filename, but that's really just for being pedantic:

    $name = "sync_common"
    $currdate = get-date -f yyyy-MM-dd
    $logfile = "c:\scripts\$name\log\$name-$currdate.txt"
    

    And here's where the trick begins:

    start-transcript -append -path $logfile
    
    write-output "starting sync"
    robocopy /mir /copyall S:\common \\10.0.0.2\common 2>&1 | Write-Output
    some_other.exe /exeparams 2>&1 | Write-Output
    ...
    write-output "ending sync"
    
    stop-transcript
    

    With start-transcript and stop-transcript you can redirect ALL output of PowerShell commands to a single file, but it doesn't work correctly with external commands. So let's just redirect all the output of those to the stdout of PS and let transcript do the rest.

    In fact, I have no idea why the MS engineers say they haven't fixed this yet "due to the high cost and technical complexities involved" when it can be worked around in such a simple way.

    Either way, running every single command with start-process is a huge clutter IMHO, but with this method, all you gotta do is append the 2>&1 | Write-Output code to each line which runs external commands.

提交回复
热议问题