-
-
Save sassdawe/91f8c48516a7fba6be16845d62dd43be to your computer and use it in GitHub Desktop.
Write an Error within a function in a nice way that displays the context of the function rather than the "Write-Error" context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using namespace System.Management.Automation | |
using namespace Microsoft.PowerShell.Commands | |
function Write-FunctionError { | |
<# | |
.SYNOPSIS | |
Writes an error within the context of the containing CmdletBinding() function. Makes error displays prettier | |
.NOTES | |
ScriptStackTrace will still show Write-FunctionError, so its not completely transparent. There's no way to "edit" or "replace" this stacktrace that I can find. | |
.EXAMPLE | |
function test { | |
[CmdletBinding()]param() | |
$badresult = 'the failed thing' | |
$badresult | Write-FunctionError 'this thing failed!' | |
} | |
#> | |
param( | |
[Parameter(Mandatory)][String]$Message, | |
[ValidateNotNullOrEmpty()][ErrorCategory]$Category = 'WriteError', | |
[ValidateNotNullOrEmpty()][String]$Id = 'FunctionError', | |
[Parameter(ValueFromPipeline)]$TargetObject | |
) | |
[PSCmdlet]$context = (Get-Variable -Scope 1 'PSCmdlet' -ErrorAction Stop).Value | |
if (-not $context) { throw 'Write-FunctionError must be used in the context of a cmdlet with [CmdletBinding()] applied' } | |
$exception = [WriteErrorException]$Message | |
$errorRecord = [ErrorRecord]::new( | |
$exception, | |
$Id, | |
$Category, | |
$TargetObject | |
) | |
$context.WriteError($errorRecord) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment