如何在 PowerShell 中检索哈希表中 value = $value 的键数?

How to retrieve a count of keys in a hashtable where the value = $value in PowerShell?

我有一个哈希表,用于存储程序集路径的版本号。我想找到最大值的键,我已经在下面的函数中解决了。我还想知道最大值的计数是否大于 1 并将其存储在变量中。关于如何完成最后一部分有什么想法吗?

Function Get-LatestDacFxPath
{
    [cmdletbinding()]
    $knownPaths = (
        'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\SQLDB\DAC0',
        'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\SQLDB\DAC0',
        'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\SQLDB\DAC0',
        'C:\Program Files (x86)\Microsoft SQL Server0\DAC\bin',
        'C:\Program Files (x86)\Microsoft SQL Server0\DAC\bin',
        'C:\Program Files (x86)\Microsoft SQL Server0\DAC\bin',
        'C:\Program Files (x86)\NuGet\Packages\Microsoft.Data.Tools.Msbuild\lib\net40'
    )

    $dacAssembly = 'Microsoft.SqlServer.Dac.dll'
    [hashtable]$dacVersions = @{}
    foreach($dacPacPath in $knownPaths) 
    {
        if(Test-Path($dacPacPath)) {
            $dacVersions[$dacPacPath] = (Get-ItemProperty -Path (Join-Path $dacPacPath $dacAssembly)).VersionInfo.ProductVersion
        }
    }

    $PathOfLatestVersion = ($dacVersions.GetEnumerator() | sort value -Descending | select -First 1 ).Key
    $LatestVersion = ($dacVersions.GetEnumerator() | sort value -Descending | select -First 1 ).Value
}

如果你想知道多个实例是否共享最高值,我会使用Group-Object:

$HighestValueBracket = $dacVersions.GetEnumerator() |Group Value |Sort {$_.Name -as [version]} -Descending |Select -First 1
if($HighestValueBracket.Count -gt 1){
    Write-Host "Multiple instances with version $($HighestValueBracket.Name)"
}

一种更简单但可能不太直观的回答方法是对值进行排序,并测试两个最大值是否相等:

$sortedVersionEntries = $dacVersions.GetEnumerator() |Sort Value -Descending
if($sortedVersionEntries[0].Value -eq $sortedVersionEntries[1]){
    Write-Host "Multiple instances with version $($sortedVersionEntries[0].Value)"
}

我最初将这个问题误读为 "how to find hashtable entry with the most items in the value field?" - 如果您只想查找包含最多项目的条目,请按值字段中的对象计数排序:

$HashTable = @{
    a = 1,2
    b = 1
    c = 1,2,3,4
    d = 1,2,3
}
$MaxEntry = $HashTable.GetEnumerator() |Sort {@($_.Value).Count} -Descending |Select -First 1
Write-Host "Key with most entries: $($MaxEntry.Key)"

将"c"写入主机