Powershell capture call stacks after error

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 would like to write arguments to function and line numbers, etc. (for example, you see in get-pscallstack)
EDIT: To clarify, this is a PowerShell stack trace, I want not a .NET one
Any ideas how to achieve this?
Dave

+5
source share
2 answers

The last error sits in:

$error[0]

Lots of good information so you can pursue, including exception stack traces. This is a small little script (Resolve-ErrorRecord that comes with PSCX) that shows a lot of good information about the latest 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
            }
        }

}
+8

, .

$error[0].ErrorRecord.ScriptStackTrace

- , .

+1

All Articles