Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash exec redirection equivalent in PowerShell

Tags:

powershell

What's PowerShell equivalent of exec redirection in bash like this?

exec 2>&1

I wanted to make a PowerShell script to redirect its stderr to stdout by itself, without any function or script block calls like this, or recursive script invocation.

The redirection should occur in the beginning of the script, then all stderr output from the rest of the script and sub-process should go to stdout.

like image 218
yaegashi Avatar asked Feb 22 '26 08:02

yaegashi


1 Answers

You can't: Unlike Bash, PowerShell has no feature for script-wide redirection of streams (as of PowerShell v7).

You'll have to do one of the very things you're trying to avoid:

  • Enclose all code in your script in . { ... } 2>&1

  • Recursively invoke your script via such an enclosure (which requires some mechanism, such as a conceptually private parameter, to prevent infinite recursion).

Also note that while stdout and stderr are the conceptual equivalents of PowerShell's success output stream and error stream, respectively:

  • PowerShell has 6 output streams in total - see about_Redirection (which your question already links to).

  • Regrettably, all of these streams are by default mapped to stdout when PowerShell is called from the outside, via its CLI.

    • However, you can selectively redirect the error stream using 2> from the outside - but none of the other streams, aside from the success stream.
like image 147
mklement0 Avatar answered Feb 25 '26 00:02

mklement0