Skip to content

Instantly share code, notes, and snippets.

@alx9r
Last active March 16, 2018 00:53
Show Gist options
  • Select an option

  • Save alx9r/3d3463cb7da2265f82b8fa1e075731ae to your computer and use it in GitHub Desktop.

Select an option

Save alx9r/3d3463cb7da2265f82b8fa1e075731ae to your computer and use it in GitHub Desktop.
test whether exceptions are thrown in different PowerShell error scenarios
Add-Type '
using System;
using System.Management.Automation;
[Cmdlet("Invoke", "ThrowTerminatingError")]
public class InvokeThrowTerminatingError : Cmdlet
{
[Parameter(ValueFromPipeline=true)]
public object InputObject { get; set; }
protected override void ProcessRecord()
{
ThrowTerminatingError(
new ErrorRecord(
new Exception("message"),
"id",
ErrorCategory.NotSpecified,
null
)
);
}
}
' -PassThru | % Assembly | Import-Module
$statement = @{
'throw' = { throw }
'ThrowTerminatingError' = { 1 | Invoke-ThrowTerminatingError }
'Write-Error' = { Write-Error 'error' }
'Write-Error -ea Stop' = { Write-Error 'error' -ea Stop }
}.'throw'
$inTry = $false
$ErrorActionPreference = 'Continue'
if ($inTry)
{
try
{
& $statement
'no exception thrown'
}
catch
{
'exception thrown'
throw
}
}
else
{
& $statement
'no exception thrown'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment