Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ThrowTerminatingError work in C#?

Tags:

c#

powershell

I have the following cmdlet written in C#, it basically just throws an error:

[Cmdlet("Use", "Dummy")]
public class UseDummyCmdlet :PSCmdlet
{
    protected override void ProcessRecord()
    {
        var errorRecord = new ErrorRecord(new Exception("Something Happened"), "SomethingHappened", ErrorCategory.CloseError, null);
        ThrowTerminatingError(errorRecord);
    }
}

I'm assuming (I could be wrong), this is the equivalent in PowerShell)

Function Use-Dummy()
{
    [CmdletBinding()]
    Param()

    process 
    {
        $errorRecord = New-Object System.Management.Automation.ErrorRecord -ArgumentList (New-Object System.Exception), 'SomethingHappened', 'NotSpecified', $null
        $PSCmdlet.ThrowTerminatingError($errorRecord) 
    }
}

The PowerShell version behaves as expected:

Use-Dummy : Exception of type 'System.Exception' was thrown.
At line:1 char:10
+ use-dummy <<<< 
    + CategoryInfo          : NotSpecified: (:) [Use-Dummy], Exception
    + FullyQualifiedErrorId : SomethingHappened,Use-Dummy

The C# version however, crashes, with the following information:

An exception of type 'System.Management.Automation.PipelineStoppedException' occurred in System.Management.Automation.dll but was not handled in user code

Additional information: The pipeline has been stopped.

What am I doing wrong?

like image 419
Jake Avatar asked Oct 30 '22 18:10

Jake


1 Answers

Can confirm, it's an environment problem, and a damn wierd one at that.

Basically if you follow the instructions here, then go to debug any binary modules, if you call ThrowTerminatingError, it crashes with PipelineStoppedException.

Now I need some kind of fix/workaround.

Edit: Found a fix, check 'enable native code debugging' in the project properties.

like image 190
Jake Avatar answered Nov 15 '22 06:11

Jake