powershellmodule

Is it possible to configure $ErrorActionPreference = 'Stop' as the default for all the functions in a powershell module?


I want all of the functions in my module to default to $ErrorActionPreference = 'Stop'. Is it possible without modifying all the functions?

I have a file per function.


Solution

  • Assuming that your module is a script module, i.e., implemented in PowerShell code:

    Important:

    I want all of the functions in my module to default to $ErrorActionPreference = 'Stop'. Is it possible without modifying all the functions?

    Yes - simply place $ErrorActionPreference = 'Stop' in your RootModule *.psm1 file's top-level code. (The RootModule entry of a module's manifest file (*.psd1) specifies a module's main module - see the docs).

    Unless overridden by the caller by using the common -ErrorAction parameter when calling your module's functions (assuming they are advanced functions), your module's top-level $ErrorActionPreference value will be in effect for all of your module's functions, except if your function directly emits a statement-terminating error[1], in which case it is the caller's $ErrorActionPreference value that matters.


    If your module is a binary module, i.e., exports compiled cmdlets (typically implemented in C#):

    Compiled cmdlets don't have their own scope - they run in the caller's scope. It is therefore the caller's $ErrorActionPreference that matters, which can be overridden on a per-call basis with common parameter -ErrorAction, but only for non-terminating errors.

    As with advanced functions in script modules, directly emitted statement-terminating errors[1] are always subject to the caller's $ErrorActionPreference value, even if -ErrorAction is used. (Note that binary cmdlets do not emit script-terminating errors).


    [1] Statement-terminating errors occur in the following scenarios: