I want to catch errors from BitsTransfer module, download link or destination not found, not accessible, required credential etc. How can I do this?
Here is the code:
Import-Module BitsTransfer
Try {
$Source = ""
Start-BitsTransfer -Source $Source -Destination "" -Priority Foreground -ErrorAction Stop
} Catch [System.Exception] {
Write-Warning "Oopsie daisy, an error popped up out of the blue!"
Break
}
If you want to inspect the details of a PowerShell error (exception), use the automatic
$_variable in thecatchblock of yourtry/catch/finallystatement.In this context,
$_refers to an instance ofSystem.Management.Automation.ErrorRecord, the type used to represent PowerShell errors.You're free to access the properties of this type, but a simple way to visualize the error message is to simply stringify the error record (either inside
"...", e.g."$_", or by calling.ToString()).Here's a simplified example:
If (presumably just for debugging) you want a nicely formatted representation of the error record, pipe it to
Format-Listwith the-Forceswitch:In PowerShell (Core) 7+ you can get an even more detailed for-display representation using the
Get-Errorcmdlet:Note:
By default, PowerShell collects all errors that occur in the session in the automatic
$Errorvariable, in reverse order (most recent first, i.e.$Error[0]).You may also collect non-terminating[1] errors that occur on a per-call basis by using the common
-ErrorVariableparameter, which is supported by cmdlets and advanced scripts/functions.The inspection techniques above can equally applied to elements of the
$Errorcollection or variable containing error records collected via-ErrorVariable; a simple example:As for what you tried:
While you can constrain
catchhandlers by the type of the .NET exception that the error record wraps, doing so is rare in practice, and there's never a good reason to constrain by[System.Exception], as any error will match it; in other words: it is redundant.Only ever use
breakandcontinueinsideswitchand loop statements (while,do,for,foreach). Otherwise, PowerShell looks up the call stack for such a statement and exits the first one it finds; if there is none, the current call stack is terminated; that is, at the very least the enclosing script terminates as a whole. See this answer for more information.To intentionally terminate the entire call stack, use a
throwstatement (which can still be caught by a caller, however).To exit the current script, use
exit(optionally with an exit code); to unconditionally return from a function, usereturn.[1] PowerShell has two fundamental error types: non-terminating ones are those occurring for individual input objects and don't prevent the command from processing other inputs, and terminating ones, which are those that cause the command to instantly terminate, and - situationally - execution overall. See this answer for more information.