Home > Blockchain >  Get the exact command error output displayed in console into a Powershell variable
Get the exact command error output displayed in console into a Powershell variable

Time:05-21

I'm writing some scripts to backup registry and I encountered 2 small issues. The 1st one is that I can't intercept the error output of the reg export command.

Example:

reg export HKEY_CURRENT_USER\Software\OpenVPN-GUI test.reg

Writes this to console because the key is not available:

ERROR: The system was unable to find the specified registry key or value.

I would love to get this exact string.

Assigning the command to a variable results in an empty string, even with Out-String:

$regerror = reg export HKEY_CURRENT_USER\Software\OpenVPN-GUI test.reg | Out-String

The closest solution I've found is this kind of redirection:

$regerror = & reg export HKEY_CURRENT_USER\Software\OpenVPN-GUI test.reg 2>&1

But that displays:

reg.exe : ERROR: The system was unable to find the specified registry key or value.
At line:1 char:9
  $test = & reg export HKEY_CURRENT_USER\Software\OpenVPN-GUI test.reg  ...
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : NotSpecified: (ERROR: The syst...y key or value.:String) [], RemoteException
      FullyQualifiedErrorId : NativeCommandError

I'm wondering if there's a simple way to get the mentioned exact output without attempting to process the text above.

CodePudding user response:

Simply convert the stderr lines to strings:

$regerror = 
  reg export HKEY_CURRENT_USER\Software\OpenVPN-GUI test.reg 2>&1 | 
    ForEach-Object ToString

While stderr are are strings to begin with, PowerShell wraps them in [System.Management.Automation.ErrorRecord] instances when you use a 2> redirection, which is what causes them to render like PowerShell errors when printed to the display. (In PowerShell (Core) 7 , they no longer render as such, but they're still wrapped in [System.Management.Automation.ErrorRecord] instances).

  • Related