1

I'm looking to get both std-err and std-out streams from a binary I have called by powershell piped to a powershell cmdlet. I cant seem to get the syntax or find the right command.

I have a little Write-Smartly cmdlet that I want to process line-by-line of combined standard-error and standard output. It is itself a wrapper on Write-Host that adds some indenting.

My first attempt, I want to:

  • use -ErrorAction to indicate to powershell not to treat standard-error messages as exceptions
  • use 2>&1 to combine standard-error and standard-output streams into a pipelineable output
  • use ... | MyCmdlet to format the combined output & error streams to their ultimate output

giving me:

& $myApp $args --% -ErrorAction 'SilentlyContinue' 2>&1 | Write-Smartly

Unfortunatly this ended up passing -ErrorAction SilentlyContinue and 2>&1 into my application as arguments. Standard-error did show up as regular output, but it was written directly to host, rather than piped to WriteSmartly.

So I made a few modifications to try to correct this:

$ErrorActionPreference = 'SilentlyContinue'
&{ & $myApp $args } 2>&1 | Write-Smartly

This simply causes my error output to disappear.

I also played around with Start-Process, but it seems too heavyweight to allow me to get things out of it with a pipe. I think that Invoke-Command or Invoke-Expression might be helpful here but I'm not sure what their use cases are.

How can I capture both standard-error and standard-output as a pipelined value in powershell?

Groostav
  • 3,170
  • 1
  • 23
  • 27
  • 2
    `& $myApp $args 2>&1 | Write-Smartly` ? What are you trying to achieve with passing `-ErrorAction` to a "binary"? – TessellatingHeckler Apr 12 '19 at 08:23
  • I'm trying to pass `-ErrorAction` to the call operator to avoid powershell treating standard-error messages as exceptions. – Groostav Apr 12 '19 at 17:38
  • 1
    The call operator doesn't take parameters, it just runs a program where the name is in a string or in a variable. If your binary is a native command (e.g. robocopy.exe) it won't throw exceptions, but PowerShell ISE and other hosts can wrap `stderr` output into ErrorRecords and make it look like they do. Are you hitting https://stackoverflow.com/questions/18380227/psexec-throws-error-messages-but-works-without-any-problems or https://github.com/PowerShell/PowerShell/issues/4002 or its linked issue https://github.com/PowerShell/PowerShell/issues/3996 ? – TessellatingHeckler Apr 12 '19 at 19:38

0 Answers0