ThrowTerminatingError如何在C#中工作?

Jak*_*ake 5 c# powershell

我有以下用C#编写的cmdlet,它基本上只是抛出一个错误:

[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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我假设(我可能是错的),这在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) 
    }
}
Run Code Online (Sandbox Code Playgroud)

PowerShell版本的行为符合预期:

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
Run Code Online (Sandbox Code Playgroud)

然而,C#版本崩溃了,包含以下信息:

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.
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Jak*_*ake 1

可以确认,这是一个环境问题,而且是一个非常奇怪的问题。

基本上,如果您按照此处的说明进行操作,然后去调试任何二进制模块,如果您调用ThrowTerminatingError,它会崩溃并显示PipelineStoppedException.

现在我需要某种修复/解决方法。

编辑:找到修复程序,在项目属性中选中“启用本机代码调试”。