-
-
Save aldrichtr/8dc8926f9396004b6342cd531d29287b 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