0

Is it possible to disable the stdout and stderr output for the following command?

req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout ./private.key -out ./mycert.crt -subj "/C=DE/ST=BW/L=Karlsruhe/O=foobar/OU=foobar/CN=foobar"

The command always produces the following output which I would like to suppress:

Generating a 2048 bit RSA private key
.............................................
.............................................................+++
........................................+++
writing new private key to './private.key'

I already tried to redirect the output with any variants of 2>&1 but his doesn't work in this scenario because of these reasons:

The openssl command is executed within a powershell session like this:

$opensslCommand = 'req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout ./private.key -out ./mycert.crt -subj "/C=DE/ST=BW/L=Karlsruhe/O=foobar/OU=foobar/CN=foobar"'
Invoke-Expression -Command $opensslCommand

Again, the redirection of the PowerShell streams doesn't work either. This wouldn't be a problem at all, but if your run the command in a non interactive mode the openssl output will be send to stderr and not to stdout.

Git behaves similar. But there you can change the output with these environment var: $env:GIT_REDIRECT_STDERR = '2>&1'

Workaround

  • Callstack:

Module Function -- calls --> Sub Function -- Invoke-Expression --> OpenSSL Command (with redirect *>$null)

  • Problem:

The error occurs because the Sub Function ist called with the ErrorAction 'Stop'. If I change it to the default Continue the output is suppressed.

To be still able to do a proper error handling I keep the global default Error Action: Stop and manually for the Invoke-Command:

$ErrorActionPreference = 'Continue'
Invoke-Expression -Command 'openssl ... *>$null'
$ErrorActionPreference = 'Stop'
OCram85
  • 841
  • 1
  • 9
  • 25
  • See `Get-Help about_redirection` or [read onlne](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_redirection?view=powershell-6) redirect all streams and pipe to out-null `*>&1 | Out-Null` –  Jan 04 '19 at 09:11
  • Thanks for your feedback. I've already tried this. But now I notice a weird behavior. The redirect works with `Invoke-Expression -Command "openssl .... 2>&1"` but not in this my module function :( – OCram85 Jan 04 '19 at 09:46

1 Answers1

1

Remember to also supress the stdout after merging stderr into it. If it doesn't work, wrap it in a scriptblock and redirect output from the entire thing, like so:

& { .\path\to\openssl.exe $opensslCommand.Split(' ') } 2>&1 1>$null
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206