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

前端 未结 4 660
孤街浪徒
孤街浪徒 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

    In order to append to a file you'll need to use a slightly different approach. You can still redirect an individual process' standard error and standard output to a file, but in order to append it to a file you'll need to do one of these things:

    1. Read the stdout/stderr file contents created by Start-Process
    2. Not use Start-Process and use the call operator, &
    3. Not use Start-Process and start the process with .NET objects

    The first way would look like this:

    $myLog = "C:\File.log"
    $stdErrLog = "C:\stderr.log"
    $stdOutLog = "C:\stdout.log"
    Start-Process -File myjob.bat -RedirectStandardOutput $stdOutLog -RedirectStandardError $stdErrLog -wait
    Get-Content $stdErrLog, $stdOutLog | Out-File $myLog -Append
    

    The second way would look like this:

    & myjob.bat 2>&1 >> C:\MyLog.txt
    

    Or this:

    & myjob.bat 2>&1 | Out-File C:\MyLog.txt -Append
    

    The third way:

    $pinfo = New-Object System.Diagnostics.ProcessStartInfo
    $pinfo.FileName = "myjob.bat"
    $pinfo.RedirectStandardError = $true
    $pinfo.RedirectStandardOutput = $true
    $pinfo.UseShellExecute = $false
    $pinfo.Arguments = ""
    $p = New-Object System.Diagnostics.Process
    $p.StartInfo = $pinfo
    $p.Start() | Out-Null
    $p.WaitForExit()
    $output = $p.StandardOutput.ReadToEnd()
    $output += $p.StandardError.ReadToEnd()
    $output | Out-File $myLog -Append
    

提交回复
热议问题