我有一个哈希表,用于存储程序集路径的版本号。我想找到最大值的关键,我已经在下面的函数中解决了。我还想知道最大值的计数是否大于1并将其存储在变量中。关于如何做最后一部分的任何想法?
Function Get-LatestDacFxPath
{
[cmdletbinding()]
$knownPaths = (
'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\SQLDB\DAC\120',
'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\SQLDB\DAC\130',
'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\SQLDB\DAC\140',
'C:\Program Files (x86)\Microsoft SQL Server\120\DAC\bin',
'C:\Program Files (x86)\Microsoft SQL Server\130\DAC\bin',
'C:\Program Files (x86)\Microsoft SQL Server\140\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
}
答案 0 :(得分:4)
如果你想弄清楚多个实例是否共享最高值,我会使用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)"
}
我最初误读了这个问题"如何在值字段中查找包含最多项目的哈希表条目?" - 如果您只想查找包含大多数项目的条目,对值字段中的对象计数进行排序:
$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"到主持人