PoshCode Logo PowerShell Code Repository

foreach-withexception (modification of post by karl prosser view diff)
diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/864"></script>download | new post

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

  1. function foreach-withexception ([scriptblock]$process,$outputexception)
  2. {
  3.   begin { $global:foreachex = @() }
  4.   process {
  5.             try
  6.             {
  7.             $local:inputitem = $_
  8.             &$process
  9.             }
  10.             catch
  11.             {
  12.             $local:exceptionitem = 1 | select-object object,exception
  13.             $local:exceptionitem.object = $local:inputitem
  14.             $local:exceptionitem.exception = $_
  15.             $global:foreachex += $local:exceptionitem
  16.             }
  17.           }
  18.   end {}
  19. }
  20. set-alias %ex foreach-withexception
  21.  
  22. 100..-5 | %ex {  "yo $_" ;  1 / $_ }
  23. $foreachex

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me