What is terminating and non-terminating errors in PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

Powershell generates two types of errors when it executes script or commands. Terminating errors and Non-Terminating errors.

Terminating error − This error generated by script, functions, or commands you create and it stops or halts the execution of the script so that the commands in the next lines can’t be executed. To handle this error proper mechanism is needed otherwise there would be an error message displayed.

For example,

PS C:\WINDOWS\system32>> This-commandnotexist
This-commandnotexist : The term 'This-commandnotexist' is not recognized as
the name of a
cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a
path was included, verify that the path is correct and try again.
At line:1 char:1
+ This-commandnotexist
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (This-commandnotexist:String)
[], CommandNotFo
+ FullyQualifiedErrorId : CommandNotFoundException

Non-Terminating Error − This error is generally generated by internal cmdlets and automatically handled by them only but the error doesn’t terminate the execution of the pipeline. You can’t handle such errors automatically because $ErrorActionPreference value is Continue by default but there are ways to handle non-terminating errors by converting them into terminating errors.

In the below example, we are going to search the logical disks on the non-existence computer.

PS C:\WINDOWS\system32>> Get-WmiObject -Class Win32_Logicaldisk -ComputerName
Get-WmiObject : The RPC server is unavailable.
At line:1 char:1
+ Get-WmiObject -Class Win32_Logicaldisk -ComputerName Nonexist
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject],
+ FullyQualifiedErrorId :
GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiO bjectCommand

The above error is generated by cmdlet and it is a non-terminating error. You can handle both the terminating and non-terminating error (by converting them into terminating error) using ErrorAction cmdlet, $ErrorActionPreference variable and try, catch, and finally blocks.

Updated on 27-May-2020 09:27:29