0
Write-Host "Errors" -BackgroundColor Red
$Error.Clear()
{Some 1200 lines code}

I want to create a table after code excution with two columns: "Error" and "Line", if there were any errors in code above. But I failed using PSCustomObject (PSObject). It doesn't create table.

[PSCustomObject] @{
     Error = $_.Exception.Message
     Line = $_.InvocationInfo.ScriptLineNumber
}

New-Object PSObject -Property @{
    Error   = $Error.Exception.Message
    Line    = $Error.InvocationInfo.ScriptLineNumber
}

Due to too many line in code I do not want to use tey/catch, so how to combine output from? Or even is it possible without using try/catch?..

$Error.Exception.Message
$Error.InvocationInfo.ScriptLineNumber
4

1 回答 1

1

To create a list of all errors that occured during a given code segment (provided non of the errors terminated execution) you could do something like this:

$Error.Clear()

# set error action preference so you don't have to add `-EA SilentlyContinue`
# to each statement
$EAPSave = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'

# ...
# your code goes here
# ...

# restore original error action preference
$ErrorActionPreference = $EAPSave

$Error | ForEach-Object {
    [PSCustomObject]@{
        'Error' = $_.Exception.Message
        'Line'  = $_.InvocationInfo.ScriptLineNumber
    }
}

Note, however, that in many cases relevant error information is hidden in nested exceptions ($_.Exception.InnerException), so the error list as produced by the code above may not be as useful as you expect.

于 2019-06-20T09:42:07.587 回答