Last active
March 16, 2018 00:53
-
-
Save alx9r/3d3463cb7da2265f82b8fa1e075731ae to your computer and use it in GitHub Desktop.
test whether exceptions are thrown in different PowerShell error scenarios
This file contains hidden or 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
| 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