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.
I want to call all the jobs with lines like this:
$p=start-process myjob.bat -redirectstandardoutput $logfile -redirecterroroutput $logfile -wait
Where do I have to put the information to append?
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:
And here's where the trick begins:
With
start-transcript
andstop-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 the2>&1 | Write-Output
code to each line which runs external commands.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:
Start-Process
&
The first way would look like this:
The second way would look like this:
Or this:
The third way:
Maybe it is not quite as elegant, but the following might also work. I suspect asynchronously this would not be a good solution.
Like Unix shells, PowerShell supports
>
redirects with most of the variations known from Unix, including2>&1
(though weirdly, order doesn't matter -2>&1 > file
works just like the normal> file 2>&1
).Like most modern Unix shells, PowerShell also has a shortcut for redirecting both standard error and standard output to the same device, though unlike other redirection shortcuts that follow pretty much the Unix convention, the capture all shortcut uses a new sigil and is written like so:
*>
.So your implementation might be: