Out-Error, the User-friendlier Write-Error

Write-Error is a pretty daunting cmdlet.  It dumps some pretty useful information to screen.  Useful, that is, for the scripter.  For the non-PowerShell-guru end user, it can be pretty intimidating. 

 

Write-Host -ForegroundColor Red might be a better option, but it doesn't populate the $Error variable.  Lastly, and this is just my preference, I'd like to have some data about where the error occurred, but I want it to look nice for the user.  This includes the script name and function name.  Instead of populating the error message manually each time, why not have PowerShell do it for me?

function Out-Error {
    param (
    [string]$message,
    [switch]$noBreak
    );
    if (!$message) { $message = 'An unspecified error occured.'; }
    Write-Error -ErrorAction SilentlyContinue $message;
    $function = (Get-Variable -scope 1 MyInvocation).Value.MyCommand.Name;
    if ($function) { $function += ":"; }
    Write-Host -ForegroundColor Red -BackgroundColor Black (
    "ERROR: (Line {0}) {1}:{2} $message" -f $MyInvocation.ScriptLineNumber,
    (Split-Path -Path $MyInvocation.ScriptName -Leaf), $function
    );
    if (!$noBreak) { break __outOfScript; }
}