15

How to emulate -ErrorAction in custom powershell function. For example consider the following script

function Foo2
{
  Write-Host "in Foo2"
  #...Error occurs 
  Foo3
}

function Foo1
{
   Write-Host "in Foo1"
   Foo2
}

function Foo3
{
   Write-Host "in Foo3"
}

PS>Foo1 -ErrorAction stop

Is it possible to stop the execution of Foo1 when error occurs in Foo2, instead of proceeding with execution of Foo3 ?

Jeevan
  • 8,532
  • 14
  • 49
  • 67

3 Answers3

22

get-help about_Functions_CmdletBindingAttribute

You want:

function Foo1() {
 [CmdletBinding()]
 PARAM()
 process{
   Write-Host "in Foo1"
   Foo2
 }
}

This is not about emulation, it means really implementing common parameters in your function; if this was your intention.


After that, you can work like this:

Foo1 -ErrorAction stop

You can use the same syntax for Foo2 and Foo3.


To log error use redirection as usual.

Matt
  • 45,022
  • 8
  • 78
  • 119
Emiliano Poggi
  • 24,390
  • 8
  • 55
  • 67
  • let me make it clear, just like how standard cmdlet will stop or continue when error occurs based on value of ErrorAction , I want even Foo1 to behave exactly like that also i would like to log the error. How can i do that ? – Jeevan May 10 '11 at 16:52
  • If you use `cmdletbinding` you can do exactly that gratis! See my edit. – Emiliano Poggi May 10 '11 at 17:04
  • Small note, the `Write-Error` calls or errors from nested commands will use that, `Write-Host` will not. :) – JasonMArcher May 10 '11 at 17:23
9

Here is a sample to illustrate @Empo Answer

function Test-ErrorAction
{
  [CmdletBinding()]
  Param( )

  begin 
  {
    Write-Host "I'am Here"    
   }

  Process 
  {
    Write-Error "coucou"
  }
  end 
  {
    Write-Host "Done !"
  }
}

clear
Test-ErrorAction -ErrorAction "silentlycontinue"
Test-ErrorAction -ErrorAction "stop"

gives

I'am Here
Done !
I'am Here
coucou
 à C:\Développements\Pgdvlp_Powershell\Sources partagées\Menus Contextuel Explorer\Test-ErrorAction.ps1: ligne:23 caractère:17
+ Test-ErrorAction  <<<< -ErrorAction "stop"
JPBlanc
  • 70,406
  • 17
  • 130
  • 175
  • 2
    NB: It's also worth noting that for `ErrorAction` to behave as you'd expect, you should raise errors with `Write-Error`. If you `throw` an exception, `ErrorAction` / `ErrorActionPreference` has no influence; the exception is a `Stop` (terminating error) by definition. https://stackoverflow.com/a/9295344/361842 – JohnLBevan Oct 23 '17 at 09:32
0
function Foo2
{
 Write-Host "in Foo2"
 Try {something} 
   Catch {
             Write-host "Foo2 blew up!"
             return
             }
 Foo3
 }
mjolinor
  • 66,130
  • 7
  • 114
  • 135