PoshCode Archive  Artifact [3856c3b4fc]

Artifact 3856c3b4fc50dc00ee1db5997729890c0e2b5415bc831909d507312c5cefd058:

  • File foreach-withexception.ps1 — part of check-in [8861eb2d12] at 2018-06-10 14:25:29 on branch trunk — simple function like foreach, but that traps exceptions using v2, and logs then in the $lastex variable. this way the pipeline can continue and process the objects that aren’t having errors happen against them. eventually this needs to be made much better, and be a v2 advanced function (user: karl prosser size: 1217)

# encoding: ascii
# api: powershell
# title: foreach-withexception
# description: simple function like foreach, but that traps exceptions using v2, and logs then in the $lastex variable. this way the pipeline can continue and process the objects that aren’t having errors happen against them. eventually this needs to be made much better, and be a v2 advanced function
# version: 0.1
# type: function
# author: karl prosser
# license: CC0
# function: foreach-withexception
# x-poshcode-id: 864
# x-archived: 2012-04-24T13:16:02
# x-published: 2009-02-12T00:56:00
#
#
function foreach-withexception ([scriptblock]$process,$outputexception)
{
  begin { $global:foreachex = @() }
  process { 
            try 
            {
            $local:inputitem = $_
            &$process 
            }
            catch
            {
            $local:exceptionitem = 1 | select-object object,exception
            $local:exceptionitem.object = $local:inputitem 
            $local:exceptionitem.exception = $_
            $global:foreachex += $local:exceptionitem
            }
          }
  end {}
}
set-alias %ex foreach-withexception

100..-5 | %ex {  "yo $_" ;  1 / $_ }
$foreachex