How do I retain ScriptStackTrace in an exception thrown from within an Invoke-Command on a remote computer? How do I retain ScriptStackTrace in an exception thrown from within an Invoke-Command on a remote computer? powershell powershell

How do I retain ScriptStackTrace in an exception thrown from within an Invoke-Command on a remote computer?


When you run some code and it fails, you receive an ErrorRecord that reflects the code you (local computer) executed. So when you use throw "error" you can access the invocationinfo and exception for that code.

When you use Invoke-Command, you are not executing throw "error" anymore, the remote computer is. You (local computer) are executing Invoke-Command ...., which is why the ErrorRecord you get reflects that (and not the real exception like you wanted). This is the way it has to be since an exception may be coming from the scriptblock the remote comptuer executed, but it could just as well be an exception from Invoke-Command itself because it couldn't connect to the remote computer or something similar.

When the exception is originally thrown on the remote computer, Invoke-Command/PowerShell throws a RemoteException on the local computer.

#Generate errorstry { Invoke-Command -ComputerName localhost -ScriptBlock { throw "error" } }catch { $remoteexception = $_ }try { throw "error" }catch { $localexception = $_ }#Get exeception-types$localexception.Exception.GetType().NameRuntimeException$remoteexception.Exception.GetType().NameRemoteException

This exception-type has a few extra properties, including SerializedRemoteException and SerializedRemoteInvocationInfo which contains the information from the exception that was thrown in the remote session. Using these, you can receive the "internal" exception.

Sample:

#Show command that threw error $localexception.InvocationInfo.PositionMessageAt line:4 char:7+ try { throw "error" }+       ~~~~~~~~~~~~~$remoteexception.Exception.SerializedRemoteInvocationInfo.PositionMessage    At line:1 char:2+  throw "error"+  ~~~~~~~~~~~~~

You can then write a simple function to extract the information dynamically, ex:

function getExceptionInvocationInfo ($ex) {    if($ex.Exception -is [System.Management.Automation.RemoteException]) {        $ex.Exception.SerializedRemoteInvocationInfo.PositionMessage    } else {        $ex.InvocationInfo.PositionMessage    }}function getException ($ex) {    if($ex.Exception -is [System.Management.Automation.RemoteException]) {        $ex.Exception.SerializedRemoteException    } else {        $ex.Exception    }}getExceptionInvocationInfo $localexceptionAt line:4 char:7+ try { throw "error" }+       ~~~~~~~~~~~~~getExceptionInvocationInfo $remoteexceptionAt line:1 char:2+  throw "error"+  ~~~~~~~~~~~~~

Be aware that the SerializedRemoteExpcetion is shown as PSObject because of the serialization/deserialization during network transfer, so if you're going to check the exception-type you need to extract it from psobject.TypeNames.

$localexception.Exception.GetType().FullNameSystem.Management.Automation.ItemNotFoundException$remoteexception.Exception.SerializedRemoteException.GetType().FullNameSystem.Management.Automation.PSObject#Get TypeName from psobject$remoteexception.Exception.SerializedRemoteException.psobject.TypeNames[0]Deserialized.System.Management.Automation.ItemNotFoundException


I am sure someone with more experience can help but I would like to give you something to chew on in the mean time. Sounds like you want to be using throw since you are looking for terminating exceptions. Write-Error does write to the error stream but it is not terminating. Regardless of your choice there my suggestion is still the same.

Capturing the exception into a variable is a good start for this so I would recommend this block from your example:

$exception = Invoke-Command -ComputerName $remoteComputerName -ScriptBlock {    try    {        throw "Test Error";    }    catch    {        return $_;    }}

$exception in this case should be a Deserialized.System.Management.Automation.ErrorRecord. You can send custom objects to throw...

You can also throw an ErrorRecord object or a Microsoft .NET Framework exception.

but in this case it does not work which is likely due to the deserialization. At one point I tried to create my own error object but some of the needed properties were read only so I skipped that.

PS M:\Scripts> throw $exceptionTest ErrorAt line:1 char:1+ throw $return+ ~~~~~~~~~~~~~    + CategoryInfo          : OperationStopped: (Test Error:PSObject) [], RuntimeException    + FullyQualifiedErrorId : Test Error

However just writing to the output stream gives you the correct information as you have seen.

PS M:\Scripts> $exceptionTest ErrorAt line:4 char:9+         throw "Test Error";+         ~~~~~~~~~~~~~~~~~~    + CategoryInfo          : OperationStopped: (Test Error:String) [], RuntimeException    + FullyQualifiedErrorId : Test Error

$exception is an object will properties that contain all of this information so a possible way to get what you need would be to make a custom error string from the desired properties. However that turned out to be more work that it was worth. A simple compromise would be to use Out-String to convert that useful output so that it can be returned as an error.

PS M:\Scripts> throw ($return | out-string)Test ErrorAt line:4 char:9+         throw "Test Error";+         ~~~~~~~~~~~~~~~~~~    + CategoryInfo          : OperationStopped: (Test Error:String) [], RuntimeException    + FullyQualifiedErrorId : Test ErrorAt line:1 char:1+ throw ($return | out-string)+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~    + CategoryInfo          : OperationStopped: (Test ErrorAt ...Test Error:String) [], RuntimeException    + FullyQualifiedErrorId : Test ErrorAt line:4 char:9+         throw "Test Error";+         ~~~~~~~~~~~~~~~~~~    + CategoryInfo          : OperationStopped: (Test Error:String) [], RuntimeException    + FullyQualifiedErrorId : Test Error

So now we have a proper terminating error with information from both relative to the scriptblock and to where in the calling code the error is generated. You will see some repetition obviously but maybe this will be a start for you.

If there is other information you need specifically I would delve into the $exception object with Get-Member to see if you can find something specific that you are looking for. Some notable properties here would be

$exception.ErrorCategory_Reason$exception.PSComputerName$exception.InvocationInfo.Line$exception.InvocationInfo.CommandOrigin

The last one would read something like this.

PS M:\Scripts> $exception.InvocationInfo.PositionMessageAt line:4 char:9+         throw "Test Error";+         ~~~~~~~~~~~~~~~~~~


Hoping someone with more experience can comment on this, my comment seems to have gone overlooked.

I found this article which offers some insight into using Enter-PSSession

Or even better, create a persistent session

$session = New-PSSession localhostInvoke-Command $session {ping example.com}Invoke-Command $session {$LASTEXITCODE}

To do debugging using tracing, remember that you need to set the VerbosePreference, DebugPreference etc in the remote session

Invoke-Command $session {$VerbosePreference = ‘continue’}Invoke-Command $session {Write-Verbose hi}