Powershell itself has a lot of good error control, but those who are used to. NET Programming prefer the try catch finally method, especially when a piece of code must be executed. Now, adweigert has come up with a good way to implement it. This function has been tested in many cases and may be helpful to you.
1 function try
2 {
3 Param
4 (
5 [scriptblock] $ command = $ (throw "the parameter-command is required ."),
6 [scriptblock] $ catch = {Throw $ _},
7 [scriptblock] $ finally = {}
8)
9
10 &{
11 $ local: erroractionpreference = "silentlycontinue"
12
13 trap
14 {
15 trap
16 {
17 &{
18 trap {Throw $ _}
19 & $ finally
20}
21
22 throw $ _
23}
24
25 $ _ | & {& $ catch}
26}
27
28 & $ command
29}
30
31 &{
32 trap {Throw $ _}
33 & $ finally
34}
35}
Example:
# Example usage
Try {
Echo ": Do some work ..."
Echo ": Try divide by zero: $(0/0 )"
}-Catch {
Echo ": cannot handle the error (will rethrow): $ _"
# Throw $ _
}-Finally {
Echo ": cleanup resources ..."
}