Throw and ThrowTerminatingError

The keyword throw raises a terminating error, for example:

throw 'Error message' 

throw may be used with a string, a message, as shown previously. throw may also be used with an exception object:

throw New-Object ArgumentException('Unsupported value') 

Or it may be used with an ErrorRecord:

throw New-Object Management.Automation.ErrorRecord( 
    (New-Object InvalidOperationException('Invalid operation')), 
    'AnErrorID', 
    [Management.Automation.ErrorCategory]::InvalidOperation, 
    $null 
) 

Commands in binary modules (Cmdlets) cannot use throw, it has a different meaning in the languages that might be used to author a Cmdlet. Cmdlets use the .NET method PSCmdlet.ThrowTerminatingError.

The ThrowTerminatingError method can be used in PowerShell in conjunction with an ErrorRecord object provided the CmdletBinding attribute is declared, for example:

function Invoke-Something { 
    [CmdletBinding()] 
    param ( ) 
 
    $errorRecord = New-Object Management.Automation.ErrorRecord( 
        (New-Object Exception('Failed')), 
        'AnErrorID', 
        [Management.Automation.ErrorCategory]::OperationStopped, 
        $null 
    ) 
    $pscmdlet.ThrowTerminatingError($errorRecord) 
} 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.37.154