Home > Back-end >  PowerShell only captures certain output when invoked with output redirection
PowerShell only captures certain output when invoked with output redirection

Time:12-02

The originally accepted answer for How To Capture Output from Non-elevated Process Run from Elevated Powershell only includes the output of git config when the BAT file invokes powershell with output redirection (>dummy.txt). All the other output is captured regardless of whether redirection is applied. Why? Is there a way to capture this output without writing to a dummy file?

CodePudding user response:

Note:

  • This answer does not address the very specific scenario described / linked to in the question.

  • Instead, it explains why the caller of runas.exe receives no output, because runas.exe itself produces none, and the launched process runs in a new window.

    • Implementing a custom IPC mechanism between the caller and the launched process may be a - complex - option, such as in the answer that prompted your question.

    • However, this alternative answer shows how you can let the runas.exe-launched process itself capture its output, as described below.


A runas.exe command invariably runs in a new console window, asynchronously from the caller's perspective, and produces no output in the caller's window.

Therefore, the only simple way to capture output from a process launched via runas.exe is to make that process itself capture its output in a file, such as via a shell's > redirection; if the target executable isn't a shell, call it via a shell's command-line interface, such as via cmd /c or powershell -c

Note that you need to call runas.exe via Start-Process -Wait if you want the caller to wait until the runas.exe-launched process has finished running, so you can retrieve and act on its complete output.

Both aspect are demonstrated in this answer.

  • Related