Last active
February 28, 2023 21:57
-
-
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
This file contains 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 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