Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Stopping Module on error without breaking calling script

$
0
0

Hi

What is the "best practice" to stop your PowerShell module on error but still respect the calling script $ErrorActionPreference?

For example:

Module "Test-Error.psm1":

function Test-Error
{
    [CmdletBinding()]
    param
    (
    )
    $ErrorActionPreference = 'Stop'
    do
    {
        'Start'

        #Write-Error 'Error Message' #-ErrorAction Stop
        Start-Process -FilePath nofile.exe

        #Return
        'DO NOT RAN THIS ON ERROR (End Module internal loop)'
    } while (1 -eq 1)
   'DO NOT RAN THIS ON ERROR (End Module external loop)' 
}

User script "Run.ps1":

$ErrorActionPreference = 'Inquire'
Test-Error
'RUN THIS (Not part of the module)'

This will stop the module execution on error as needed, but also stop the "user script" Run.ps1 overriding his ErrorActionPreference  so 'RUN THIS (Not part of the module)' will not run which is not desirable.

Can I use "$ErrorActionPreference = 'Stop'" or "-ErrorAction Stop" inside the module without braking the user script? separating the user script and the module "Scope" in some way maybe?
Or do I have to use "try...catch" and "Return" combination instead?

Thank you



Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>