Emulating -ErrorAction in powershell user-defined function

How to emulate -ErrorAction in user 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 an error occurs in Foo2 instead of continuing to execute Foo3 even after an error in Foo2?

Regards, Jeez

+6
source share
3 answers

get-help about_Functions_CmdletBindingAttribute

Do you want to:

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

This is not about emulation, it means that you really implement common parameters in your function; if that was your intention.


After that you can work as follows:

  Foo1 -ErrorAction stop

You can use the same syntax for Foo2 and Foo3 .


To transfer the error to the log, as usual,

+8
source

Here is an example illustrating @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" 
+5
source
 function Foo2 { Write-Host "in Foo2" Try {something} Catch { Write-host "Foo2 blew up!" return } Foo3 } 
0
source

Source: https://habr.com/ru/post/887720/


All Articles