I want to capture and log all output (redirecting stderr) from Invoke-Expression calls, but by doing that any exception that would normally be thrown seems to be swallowed.
Assuming c:\temp\test already exists this command will throw an exception:
PS U:\> $cmd = "mkdir c:\temp\test"
PS U:\> $output = Invoke-Expression $cmd
New-Item : Item with specified name C:\temp\test already exists.
At line:38 char:24
+ $scriptCmd = {& <<<< $wrappedCmd -Type Directory @PSBoundParameters }
+ CategoryInfo : ResourceExists: (C:\temp\test:String) [New-Item], IOException
+ FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand
But, if I redirect stderr, then nothing happens:
PS U:\> $cmd = "mkdir c:\temp\test 2>&1"
PS U:\> $output = Invoke-Expression $cmd
PS U:\>
This is a simplified example, and I'm using Invoke-Expression in a function for many types of calls, and logging the output. So it is not just a matter of making this call work.
Furthermore not capturing the output will also throw the exception correctly:
PS U:\> $cmd = "mkdir c:\temp\test 2>&1"
PS U:\> Invoke-Expression $cmd
New-Item : Item with specified name C:\temp\test already exists.
At line:38 char:24
+ $scriptCmd = {& <<<< $wrappedCmd -Type Directory @PSBoundParameters }
+ CategoryInfo : ResourceExists: (C:\temp\test:String) [New-Item], IOException
+ FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand
I see that $Error actually contains the exception, but I don't know if I can be sure that it contains only errors related to the Invoke-Expression call.
But the question stands. How can I capture all output (including stderr) from Invoke-Expression, and still get exceptions thrown?