diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index efbdd4d7a74..36b7a484913 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -3698,7 +3698,9 @@ internal void RemoveVariableListsInPipe() if (this.PipelineVariable != null) { this.OutputPipe.RemovePipelineVariable(); - _state.PSVariable.Remove(this.PipelineVariable); + // '_state' could be null when a 'DynamicParam' block runs because the 'DynamicParam' block runs in 'DoPrepare', + // before 'PipelineProcessor.SetupParameterVariables' is called, where '_state' is initialized. + _state?.PSVariable.Remove(this.PipelineVariable); } } } diff --git a/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 b/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 index 6f660e89151..299060c6275 100644 --- a/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 +++ b/test/powershell/engine/ParameterBinding/ParameterBinding.Tests.ps1 @@ -283,6 +283,17 @@ Describe "Parameter Binding Tests" -Tags "CI" { } } + It "PipelineVariable shouldn't cause a NullRef exception when 'DynamicParam' block is present" { + function DynamicParamTest { + [CmdletBinding()] + param() + dynamicparam { } + process { 'hi' } + } + + DynamicParamTest -PipelineVariable bar | ForEach-Object { $bar } | Should -Be "hi" + } + Context "Use automatic variables as default value for parameters" { BeforeAll { ## Explicit use of 'CmdletBinding' make it a script cmdlet