Skip to content

Instantly share code, notes, and snippets.

@JustinGrote
Last active February 28, 2023 21:57
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save JustinGrote/81646571496d1378cf6ce37c7c7d1b81 to your computer and use it in GitHub Desktop.
Save JustinGrote/81646571496d1378cf6ce37c7c7d1b81 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 errr displays prettier
#>
param(
[Parameter(Mandatory)][String]$Message,
[ValidateNotNullOrEmpty()][ErrorCategory]$Category = 'WriteError',
[ValidateNotNullOrEmpty()][String]$Id = 'FunctionError',
[Parameter(ValueFromPipeline)]$TargetObject,
[PSCmdlet]$context = $PSCmdlet.SessionState.PSVariable.GetValue('PSCmdlet')
)
# 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