I am using Powershell's trap feature because I would like to output full error information when there's an error and I have to reply to the error. Without the use of a trap Powershell will not show me the error information until after the error (and whatever Inquire prompt I responded to).
The problem with using the trap feature is that though I can print the full information using $error[0]
I can't figure out how to copy it to a string and get the full information. Instead I only get the brief information.
For example, this shows the full information:
$ErrorActionPreference = "Stop"
trap {$error[0]; Read-Host -Prompt "Trapped. Press Enter to exit"}
Split-Path -BAD
echo "Running script"
Read-Host -Prompt "Press Enter to exit"
Split-Path : A parameter cannot be found that matches parameter name 'BAD'.
At line:3 char:12
+ Split-Path -BAD
+ ~~~~
+ CategoryInfo : InvalidArgument: (:) [Split-Path], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SplitPathCo
mmand
Trapped. Press Enter to exit:
Split-Path : A parameter cannot be found that matches parameter name 'BAD'.
At line:3 char:12
+ Split-Path -BAD
+ ~~~~
+ CategoryInfo : InvalidArgument: (:) [Split-Path], ParentContainsErrorRecordExce
ption
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SplitPathCo
mmand
But if I try to use $error[0] from Write-Host it only shows the brief error information:
$ErrorActionPreference = "Stop"
trap {Write-Host -ForegroundColor Red -BackgroundColor Black "$($error[0])"; Read-Host -Prompt "Trapped. Press Enter to exit"}
Split-Path -BAD
echo "Running script"
Read-Host -Prompt "Press Enter to exit"
A parameter cannot be found that matches parameter name 'BAD'.
Trapped. Press Enter to exit:
Split-Path : A parameter cannot be found that matches parameter name 'BAD'.
At line:3 char:12
+ Split-Path -BAD
+ ~~~~
+ CategoryInfo : InvalidArgument: (:) [Split-Path], ParentContainsErrorRecordExce
ption
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SplitPathCo
mmand
I want to show the full error information from the trap with color which is why I need Write-Host.