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
- 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
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.
PowerShell Code Repository