diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 80ba4545ff4..464d8e202b1 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -4580,13 +4580,20 @@ internal static IEnumerable CompleteFilename(CompletionContext return CommandCompletion.EmptyCompletionResult; } - var lastAst = context.RelatedAsts[^1]; - if (lastAst.Parent is UsingStatementAst usingStatement - && usingStatement.UsingStatementKind is UsingStatementKind.Module or UsingStatementKind.Assembly - && lastAst.Extent.File is not null) + if (context.RelatedAsts != null && context.RelatedAsts.Count > 0) { - relativeBasePath = Directory.GetParent(lastAst.Extent.File).FullName; - _ = currentPS.AddParameter("RelativeBasePath", relativeBasePath); + var lastAst = context.RelatedAsts[^1]; + if (lastAst.Parent is UsingStatementAst usingStatement + && usingStatement.UsingStatementKind is UsingStatementKind.Module or UsingStatementKind.Assembly + && lastAst.Extent.File is not null) + { + relativeBasePath = Directory.GetParent(lastAst.Extent.File).FullName; + _ = currentPS.AddParameter("RelativeBasePath", relativeBasePath); + } + else + { + relativeBasePath = context.ExecutionContext.SessionState.Internal.CurrentLocation.ProviderPath; + } } else { diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 046d00b442f..9582ad72074 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -4012,4 +4012,10 @@ Describe "WSMan Config Provider tab complete tests" -Tags Feature,RequireAdminOn # https://github.com/PowerShell/PowerShell/issues/4744 # TODO: move to test cases above once working } + + It "[CompletionCompleters]::CompleteFilename should not throw NullReferenceException with empty string" { + { [System.Management.Automation.CompletionCompleters]::CompleteFilename("") } | Should -Not -Throw + $result = [System.Management.Automation.CompletionCompleters]::CompleteFilename("") + $result | Should -Not -BeNullOrEmpty + } }