From 99d09f71bea0dd522725dcfde018b0c4834ec60a Mon Sep 17 00:00:00 2001 From: Jake Bolton Date: Tue, 28 May 2024 18:14:53 -0500 Subject: [PATCH] Create Function-Using-Clean-Block.ps1 --- Pwsh/Pipeline/Function-Using-Clean-Block.ps1 | 60 ++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Pwsh/Pipeline/Function-Using-Clean-Block.ps1 diff --git a/Pwsh/Pipeline/Function-Using-Clean-Block.ps1 b/Pwsh/Pipeline/Function-Using-Clean-Block.ps1 new file mode 100644 index 0000000..43da356 --- /dev/null +++ b/Pwsh/Pipeline/Function-Using-Clean-Block.ps1 @@ -0,0 +1,60 @@ +#Requires -Version 7.3 + +'See: ' + +function DoStuff { + [CmdletBinding()] + param( + # throw an exception that's handled + [switch]$ForceFail, + + # throws an exception type that's not expected + [switch]$ForceUnexpected + ) + end { + sleep .75 + if( $ForceUnexpected ) { + Get-Item -ea 'Stop' 'foo\bar\does\not-exist.md' + } + if( $ForceFail ) { + throw 'Bad🔴' + } + 'Good🟢' + } + clean { + # 7.3+ added the clean {... } block. + # see more: + 'DoStuff() => clean' | write-host -fore blue + } +} +function Main { + param( + [switch]$ForceFail, + [switch]$ForceUnexpected + ) + try { + 'Main() => try ' | write-host -fore blue + DoStuff -ForceFail $ForceFail -ForceUnexpected $ForceUnexpected + } catch { + if( $_.ToString() -match 'bad🔴' ) { + 'Main() => expected fail' + } else { + throw $_ # let other error types bubble + } + } + finally { + 'Main() => finally' | write-host -fore blue + } +} + +## Examples +DoStuff # clean. no errors +DoStuff -ForceFail # force the expecteded error +DoStuff -ForceUnexpected # force the expecteded error + +## examples wrapping DoStuff +Main +Main -ForceFail +DoStuff -ForceUnexpected:$false +# DoStuff -ForceUnexpected:$false -ForceFail +# DoStuff -ForceUnexpected:$true