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:
- Read the stdout/stderr file contents created by
Start-Process
- Not use Start-Process and use the call operator,
&
- 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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…