1

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.

0

1 Answer 1

4

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).

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, that's what I was missing!
Glad to hear it, @Destroy666; my pleasure.
But why won't the powershell errors be included in "foreach-object"? How can we debug such behaviors with object inspection?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.