diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index 8071679d63..9956cf9fa9 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -516,7 +516,8 @@ namespace System.Management.Automation // If we were invoked from TabExpansion2, we want to "remove" TabExpansion2 and anything it calls // from our results. We do this by faking out the session so that TabExpansion2 isn't anywhere to be found. SessionStateScope scopeToRestore; - if (context.CurrentCommandProcessor.Command.CommandInfo.Name.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase) + if (context.CurrentCommandProcessor is not null + && context.CurrentCommandProcessor.Command.CommandInfo.Name.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase) && context.CurrentCommandProcessor.UseLocalScope && context.EngineSessionState.CurrentScope.Parent is not null) { diff --git a/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 b/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 index dabb215cb1..e0ec96aa87 100644 --- a/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 @@ -87,4 +87,21 @@ Describe "Tab completion bug fix" -Tags "CI" { $result.CompletionMatches[0].CompletionText | Should -BeExactly 'Ascending' $result.CompletionMatches[1].CompletionText | Should -BeExactly 'Descending' } + + It "Issue#19912 - Tab completion should not crash" { + $ISS = [initialsessionstate]::CreateDefault() + $Runspace = [runspacefactory]::CreateRunspace($ISS) + $Runspace.Open() + $OldRunspace = [runspace]::DefaultRunspace + try + { + [runspace]::DefaultRunspace = $Runspace + {[System.Management.Automation.CommandCompletion]::CompleteInput('Get-', 3, $null)} | Should -Not -Throw + } + finally + { + [runspace]::DefaultRunspace = $OldRunspace + $Runspace.Dispose() + } + } }