在抛出错误后,powershell捕获调用堆栈

Dav*_*yes 5 error-handling powershell callstack

我想做这样的事......

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

理想情况下,我想捕获函数和行号的参数等(就像你在get-pscallstack中看到的那样)
编辑:澄清一下,它是powershell堆栈跟踪我想要的不是.NET一个
任何想法如何实现这一点?
戴夫

Kei*_*ill 8

最后一个错误是:

$error[0]
Run Code Online (Sandbox Code Playgroud)

有很多好的信息供你追查,包括异常堆栈跟踪.这是一个小巧的小脚本(PSLCX附带的Resolve-ErrorRecord),它显示了很多关于上一个错误的好信息:

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
            }
        }

}
Run Code Online (Sandbox Code Playgroud)