Reputation: 3016
How do I obtain the stack trace of an exception thrown on a remote computer?
This question is almost identical, however the asker was satisfied with getting the SerializedRemoteInvocationInfo.PositionMessage. My situation has multiple scripts calling one another, so I need the full call stack to understand my problem.
The following snippet shows an empty stack trace:
$session = New-PSSession -ComputerName AComputer -UseSSL
$script = {C:\AScriptThatFails.ps1}
try{
Invoke-Command -Session $session -ScriptBlock $script
}
catch{
Write-Output = $_.Exception.SerializedRemoteException.StackTrace #Empty!?
}
Upvotes: 1
Views: 208
Reputation: 438273
It looks like the error record's .ScriptStackTrace
property contains the remote script execution's stack trace:
try {
Invoke-Command -ErrorAction Stop -Session $session -ScriptBlock $script
}
catch {
$_ # output the error record
$_.ScriptStackTrace # output the script stack trace
}
Note the use of -ErrorAction Stop
to escalate remote errors to script-terminating ones, so that the try
/ catch
handler is triggered by any error, not just by script-terminating ones (that is, also by non-terminating and statement-terminating errors).
If this escalation is undesired, use the following technique:
$hadScriptTerminatingError = $false
try {
# User -ErrorVariable to collect the errors that occur.
Invoke-Command -Session $session -ScriptBlock $script -ErrorVariable errs
} catch { $hadScriptTerminatingError = $true }
$succeeded = $? -and -not $hadScriptTerminatingError
# Analyze the collected errors, if any.
foreach ($err in $errs) {
$err # output the error record
$err.ScriptStackTrace # output the script stack trace
}
Upvotes: 1