The throw keyword raises a terminating error, as in the following example:
throw 'Error message'
Existing exception types are documented in the .NET framework; each is ultimately derived from the System.Exception type found in the .NET reference:
https://docs.microsoft.com/en-us/dotnet/api/system.exception?view=netframework-4.7.2
throw may be used with a string or a message, as shown previously. throw may also be used with an exception object:
throw [ArgumentException]::new('Unsupported value')
Or it may be used with ErrorRecord:
throw [System.Management.Automation.ErrorRecord]::new( [InvalidOperationException]::new('Invalid operation'), 'AnErrorID', [System.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 PSCmdlet.ThrowTerminatingError .NET method.
The ThrowTerminatingError method can be used in PowerShell in conjunction with an ErrorRecord object, provided the CmdletBinding attribute is declared, as in the example:
function Invoke-Something { [CmdletBinding()] param ( ) $errorRecord = [System.Management.Automation.ErrorRecord]::new( [InvalidOperationException]::new('Failed'), 'AnErrorID', [System.Management.Automation.ErrorCategory]::OperationStopped, $null ) $pscmdlet.ThrowTerminatingError($errorRecord) }