powershellio-redirectiontrailing-newline

Powershell: stdout and stderr to separate files, without new lines


I'm trying to store the stdout and stderr outputs of a command to two separate files. I'm doing this like so:

powershell.exe @_cmd 2>"stderr.txt" >"stdout.txt"

Where $_cmd is an arbitrary string command.

This works, but the output files have newlines appended after the output. I'd like to modify this to eliminate the newlines. I know you can use cmd | Out-File ... -NoNewline or [System.IO.File]::WriteAllText(..., [System.Text.Encoding]::ASCII), but I'm not sure how to accomplish this with the stderr output.

EDIT: I've realized that the issue isn't the trailing new line specifically (although I still want to remove it), but the fact that I need the output file to be UTF-8 encoded. The trailing new line is not a valid UTF-8 character apparently, which is what's causing me grief. Perhaps there's a way to capture the stderr and stdout to separate variables, and then use Out-File -Encoding utf8?


Solution

  • @TheMadTechnician's comment held the answer that worked.

    $process = Start-Process powershell.exe -ArgumentList "$_cmd" -Wait -PassThru -NoNewWindow -RedirectStandardError "stderr.txt" -RedirectStandardOutput "stdout.txt"
    $exitcode = $process.ExitCode