From bbb11dd07a194a33d29fbe7b1dcd359e3631732a Mon Sep 17 00:00:00 2001 From: Dongbo Wang Date: Thu, 3 Feb 2022 19:39:08 +0000 Subject: [PATCH] Fix the clean block for generated proxy function (#16827) --- .../engine/CommandMetadata.cs | 4 +++- .../Language/Scripting/PipelineBehaviour.Tests.ps1 | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/System.Management.Automation/engine/CommandMetadata.cs b/src/System.Management.Automation/engine/CommandMetadata.cs index bbe2b6666b..a9094f54b3 100644 --- a/src/System.Management.Automation/engine/CommandMetadata.cs +++ b/src/System.Management.Automation/engine/CommandMetadata.cs @@ -1128,7 +1128,9 @@ clean // 1. the 'Clean' block doesn't propagate up any exception (terminating error); // 2. only one expression in the script, so nothing else needs to be stopped when invoking the method fails. return @" - $steppablePipeline.Clean() + if ($null -ne $steppablePipeline) { + $steppablePipeline.Clean() + } "; } diff --git a/test/powershell/Language/Scripting/PipelineBehaviour.Tests.ps1 b/test/powershell/Language/Scripting/PipelineBehaviour.Tests.ps1 index 9551343da8..0478492c91 100644 --- a/test/powershell/Language/Scripting/PipelineBehaviour.Tests.ps1 +++ b/test/powershell/Language/Scripting/PipelineBehaviour.Tests.ps1 @@ -478,6 +478,19 @@ Describe 'Function Pipeline Behaviour' -Tag 'CI' { ## Dispose the steppable pipeline. $step.Dispose() } + + It "Clean block runs fine in a proxy function when a dynamic parameter fails to bind" { + $function:TestProxyGci = [scriptblock]::Create( + [Management.Automation.ProxyCommand]::Create( + (Get-Command Get-ChildItem))) + + ## The proxy function 'TestProxyGci' contains the 'dynamicparam' block, which will + ## run during parameter binding. However, the parameter binding failed, and thus + ## the 'begin', 'process', and 'end' blocks will not run, so '$steppablePipeline' + ## in the proxy function is null (never created). The 'clean' block will run anyway, + ## but it should skip calling '$steppablePipeline.Clean()' in this case. + { TestProxyGci -Attributes } | Should -Throw -ErrorId 'MissingArgument,TestProxyGci' + } } Context "'exit' statement in command" {