Skip to content

Commit 99d09f7

Browse files
authored
Create Function-Using-Clean-Block.ps1
1 parent e3f50b7 commit 99d09f7

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#Requires -Version 7.3
2+
3+
'See: <https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_methods?view=powershell-7.4#clean>'
4+
5+
function DoStuff {
6+
[CmdletBinding()]
7+
param(
8+
# throw an exception that's handled
9+
[switch]$ForceFail,
10+
11+
# throws an exception type that's not expected
12+
[switch]$ForceUnexpected
13+
)
14+
end {
15+
sleep .75
16+
if( $ForceUnexpected ) {
17+
Get-Item -ea 'Stop' 'foo\bar\does\not-exist.md'
18+
}
19+
if( $ForceFail ) {
20+
throw 'Bad🔴'
21+
}
22+
'Good🟢'
23+
}
24+
clean {
25+
# 7.3+ added the clean {... } block.
26+
# see more: <https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_methods?view=powershell-7.4#clean>
27+
'DoStuff() => clean' | write-host -fore blue
28+
}
29+
}
30+
function Main {
31+
param(
32+
[switch]$ForceFail,
33+
[switch]$ForceUnexpected
34+
)
35+
try {
36+
'Main() => try ' | write-host -fore blue
37+
DoStuff -ForceFail $ForceFail -ForceUnexpected $ForceUnexpected
38+
} catch {
39+
if( $_.ToString() -match 'bad🔴' ) {
40+
'Main() => expected fail'
41+
} else {
42+
throw $_ # let other error types bubble
43+
}
44+
}
45+
finally {
46+
'Main() => finally' | write-host -fore blue
47+
}
48+
}
49+
50+
## Examples
51+
DoStuff # clean. no errors
52+
DoStuff -ForceFail # force the expecteded error
53+
DoStuff -ForceUnexpected # force the expecteded error
54+
55+
## examples wrapping DoStuff
56+
Main
57+
Main -ForceFail
58+
DoStuff -ForceUnexpected:$false
59+
# DoStuff -ForceUnexpected:$false -ForceFail
60+
# DoStuff -ForceUnexpected:$true

0 commit comments

Comments
 (0)