Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sassdawe/91f8c48516a7fba6be16845d62dd43be to your computer and use it in GitHub Desktop.
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
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