diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index e11b3c30f8c..7beb1f32590 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -339,7 +339,13 @@ public PSTypeName[] ParameterType [Parameter(ParameterSetName = "AllCommandSet")] public SwitchParameter UseFuzzyMatching { get; set; } - private readonly List _commandScores = new List(); + /// + /// Gets or sets the minimum fuzzy matching distance. + /// + [Parameter(ParameterSetName = "AllCommandSet")] + public uint FuzzyMinimumDistance { get; set; } = 5; + + private List _commandScores = new List(); /// /// Gets or sets the parameter that determines if return cmdlets based on abbreviation expansion. @@ -501,13 +507,16 @@ private void OutputResultsHelper(IEnumerable results) if (UseFuzzyMatching) { - results = _commandScores.OrderBy(static x => x.Score).Select(static x => x.Command).ToList(); + _commandScores = _commandScores + .Where(x => x.Score <= FuzzyMinimumDistance) + .OrderBy(static x => x.Score) + .ToList(); + results = _commandScores.Select(static x => x.Command); } int count = 0; foreach (CommandInfo result in results) { - count += 1; // Only write the command if it is visible to the requestor if (SessionState.IsVisible(origin, result)) { @@ -532,11 +541,21 @@ private void OutputResultsHelper(IEnumerable results) } else { - // Write output as normal command info object. - WriteObject(result); + if (UseFuzzyMatching) + { + PSObject obj = new PSObject(result); + obj.Properties.Add(new PSNoteProperty("Score", _commandScores[count].Score)); + WriteObject(obj); + } + else + { + WriteObject(result); + } } } } + + count += 1; } #if LEGACYTELEMETRY diff --git a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Command.Tests.ps1 b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Command.Tests.ps1 index 1292992b092..a07ed78e753 100644 --- a/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Command.Tests.ps1 +++ b/test/powershell/Modules/Microsoft.PowerShell.Utility/Get-Command.Tests.ps1 @@ -7,6 +7,7 @@ Describe "Get-Command Feature tests" -Tag Feature { $cmds = Get-Command get-hlp -UseFuzzyMatch $cmds.Count | Should -BeGreaterThan 0 $cmds[0].Name | Should -BeExactly 'Get-Help' -Because "This should be closest match so shows up first" + $cmds[0].Score | Should -Be 1 } It "Should match native commands" { @@ -20,6 +21,14 @@ Describe "Get-Command Feature tests" -Tag Feature { $cmds.Count | Should -BeGreaterThan 0 $cmds.Name | Should -Contain $expectedcmd } + + It "Should use minimum distance" { + $cmds = Get-Command get-hlp -UseFuzzyMatch -FuzzyMinimumDistance 3 + $cmds.Count | Should -BeGreaterThan 0 + foreach ($cmd in $cmds) { + $cmd.Score | Should -BeLessOrEqual 3 + } + } } Context "-UseAbbreviationExpansion tests" {