About trap
All the way back in PowerShell 1.0, a trap
statement was the only way to handle terminating errors in a script.
As trap
very occasionally finds its way into modern scripts, it is beneficial to understand the use of the statement. One possible use in modern scripts might be to log unhandled or unanticipated errors in a script.
trap
is used to catch errors raised anywhere within the scope of the trap
declaration, that is, the current scope and any child scopes.
The PowerShell engine finds trap
statements anywhere within a script before beginning the execution of the script. It deviates from the line-by-line approach you might expect when running a PowerShell script. When PowerShell was first released, this made trap
quite confusing to use.
trap
is one of the statements within PowerShell that are read when a script is parsed and before it is run. Such statements are not affected by their position within the script. Other examples of parse-time statements include...