# 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