Home > Net >  How can I write to file descriptor 3 via pwsh on linux
How can I write to file descriptor 3 via pwsh on linux

Time:11-05

I'm using pwsh on linux to run some specific powershell modules.

I want to output the data received to file descriptor 3. I want data on file descriptor 3 as Powershell doesn't respect the convention that stdout is data and stderr is logging. I want file descriptor 3 to serve as our "data" file descriptor.

End goal is to be able to do something like this as we wrap this powershell call in Python and we'll redirect the file descriptor 3 data ourselves

pwsh -f script.ps1 3>data

CodePudding user response:

PowerShell has no built-in way to output to streams other than stdout (1) and stderr (2) (more on that below.

Conceivably, you can roll your own output behavior with .NET API and/or P/Invoke calls, but that would be cumbersome.

However, this may not be required:

  • While it is true that - unfortunately - PowerShell by default sends output from all its output streams to stdout - see GitHub issue #7989 - you can redirect PowerShell error-stream to stderr, if you apply a 2> redirection on the caller's side.

The following call, e.g. from bash, demonstrates this:

# Prints just 'hi', because the error-stream output was
# redirected to stderr thanks to 2>, and due to targeting /dev/null, suppressed.
pwsh -noprofile -c '"hi"; Write-Error no!' 2>/dev/null

The downside is that if you want to print the stderr output too, you must capture it in a file and print it afterwards, which means that it (a) won't appear at the time it is being produced and (b) therefore won't be properly interleaved with any stdout output.

  • Related