Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell capture call stack after an error is thrown

I want to do something like this...

try  
{  
    # Something in this function throws an exception
    Backup-Server ...  
}catch  
{  
    # Capture stack trace of where the error was thrown from
    Log-Error $error 
}

Ideally I'd like to capture arguments to the function and line numbers etc. (like you see in get-pscallstack)
EDIT: To clarify, it's the powershell stack trace I want not the .NET one
Any ideas how to achieve this?
Dave

like image 645
David Hayes Avatar asked Mar 11 '10 21:03

David Hayes


2 Answers

The last error is sitting in:

$error[0]

Lots of good info in there for you to chase down including exception stack traces. This is a handly little script (Resolve-ErrorRecord that ships with PSCX) that shows lots of good info about the last error:

param(
    [Parameter(Position=0, ValueFromPipeline=$true)]
    [ValidateNotNull()]
    [System.Management.Automation.ErrorRecord[]]
    $ErrorRecord
)
process {

        if (!$ErrorRecord)
        {
            if ($global:Error.Count -eq 0)
            {
                Write-Host "The `$Error collection is empty."
                return
            }
            else
            {
                $ErrorRecord = @($global:Error[0])
            }
        }
        foreach ($record in $ErrorRecord)
        {
            $record | Format-List * -Force
            $record.InvocationInfo | Format-List *
            $Exception = $record.Exception
            for ($i = 0; $Exception; $i++, ($Exception = $Exception.InnerException))
            {
                "$i" * 80
               $Exception | Format-List * -Force
            }
        }

}
like image 197
Keith Hill Avatar answered Nov 15 '22 09:11

Keith Hill


You don't need as much code as Keith's answer.

$error[0].ErrorRecord.ScriptStackTrace

is what you want.

like image 27
Duncan Avatar answered Nov 15 '22 08:11

Duncan