Powershell – Emulating -ErrorAction in custom powershell function

powershell

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 ?

Best Answer

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.