Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions src/System.Management.Automation/engine/GetCommandCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,13 @@ public PSTypeName[] ParameterType
[Parameter(ParameterSetName = "AllCommandSet")]
public SwitchParameter UseFuzzyMatching { get; set; }

private readonly List<CommandScore> _commandScores = new List<CommandScore>();
/// <summary>
/// Gets or sets the minimum fuzzy matching distance.
/// </summary>
[Parameter(ParameterSetName = "AllCommandSet")]
public uint FuzzyMinimumDistance { get; set; } = 5;

private List<CommandScore> _commandScores = new List<CommandScore>();

/// <summary>
/// Gets or sets the parameter that determines if return cmdlets based on abbreviation expansion.
Expand Down Expand Up @@ -501,13 +507,16 @@ private void OutputResultsHelper(IEnumerable<CommandInfo> 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))
{
Expand All @@ -532,11 +541,21 @@ private void OutputResultsHelper(IEnumerable<CommandInfo> 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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" {
Expand All @@ -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" {
Expand Down