You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何列出解决方案中过时NuGet包并按过时时长排序以便手动更新?

解决方案:按发布日期差优先级更新NuGet包

一、PowerShell脚本实现

可以通过PowerShell脚本遍历项目包、计算版本发布日期差并排序,输出更新优先级列表,甚至自动执行更新。

脚本示例

# 确保NuGet包提供程序已加载
Install-PackageProvider -Name NuGet -Force -Scope CurrentUser
Import-PackageProvider NuGet

# 替换为你的项目/解决方案路径
$projectPath = "YourProject.csproj"
$projectName = Split-Path $projectPath -Leaf

# 获取项目中已安装的NuGet包
$installedPackages = Get-Package -ProjectName $projectName

$packageUpdateList = @()

foreach ($pkg in $installedPackages) {
    # 获取该包的最新稳定版信息
    $latestStable = Find-Package -Name $pkg.Id -AllVersions | 
                    Where-Object { !$_.IsPrerelease } | 
                    Sort-Object PublishedDate -Descending | 
                    Select-Object -First 1

    if ($latestStable -and $latestStable.Version -ne $pkg.Version) {
        # 计算版本发布日期差值(天数)
        $daysOutdated = ($latestStable.PublishedDate - $pkg.PublishedDate).Days

        $packageUpdateList += [PSCustomObject]@{
            Id = $pkg.Id
            CurrentVersion = $pkg.Version.ToString()
            LatestVersion = $latestStable.Version.ToString()
            DaysOutdated = $daysOutdated
            CurrentPublishDate = $pkg.PublishedDate.ToString("yyyy-MM-dd")
            LatestPublishDate = $latestStable.PublishedDate.ToString("yyyy-MM-dd")
        }
    }
}

# 按过时天数降序排序(最久的在前)
$sortedPackages = $packageUpdateList | Sort-Object DaysOutdated -Descending

# 输出优先级列表
Write-Host "NuGet包更新优先级(按过时最久排序):" -ForegroundColor Cyan
$sortedPackages | Format-Table Id, CurrentVersion, LatestVersion, DaysOutdated -AutoSize

# 可选:自动执行更新(取消注释以下代码)
# foreach ($item in $sortedPackages) {
#     Write-Host "正在更新 $($item.Id) 至 $($item.LatestVersion)..." -ForegroundColor Yellow
#     Update-Package -Id $item.Id -ProjectName $projectName -Version $item.LatestVersion
# }

使用说明

  • 替换$projectPath为你的项目文件或解决方案路径。
  • 脚本会先列出所有需更新的包,按过时天数从大到小排序。
  • 若需要自动更新,取消注释最后一段循环代码即可。

二、NuGet命令行+Python脚本方案

如果偏好命令行操作,可以结合nuget命令和Python脚本解析输出、排序并生成更新命令。

Python脚本示例

import subprocess
from datetime import datetime
import xml.etree.ElementTree as ET

# 替换为你的项目路径
project_path = "YourProject.csproj"

# 1. 获取项目中引用的包及其当前版本
ns = {"msbuild": "http://schemas.microsoft.com/developer/msbuild/2003"}
tree = ET.parse(project_path)
root = tree.getroot()
current_packages = {}
for ref in root.findall(".//msbuild:PackageReference", ns):
    pkg_id = ref.get("Include")
    current_version = ref.get("Version")
    current_packages[pkg_id] = current_version

# 2. 获取每个包的最新稳定版及发布日期
package_info = {}
for pkg_id in current_packages.keys():
    # 获取当前版本的发布日期
    current_date_result = subprocess.run(
        ["nuget", "show", pkg_id, "-Version", current_packages[pkg_id], "-Properties", "PublishedDate"],
        capture_output=True, text=True
    )
    current_date_str = current_date_result.stdout.split(":")[-1].strip()
    current_date = datetime.strptime(current_date_str, "%Y-%m-%d")

    # 获取最新稳定版的信息
    latest_result = subprocess.run(
        ["nuget", "list", pkg_id, "-AllVersions", "-Prerelease", "false"],
        capture_output=True, text=True
    )
    latest_lines = latest_result.stdout.splitlines()
    latest_version = None
    latest_date = None
    for line in latest_lines:
        if not line.strip():
            continue
        parts = line.split()
        ver = parts[1]
        date_str = parts[-1]
        date = datetime.strptime(date_str, "%Y-%m-%d")
        if not latest_date or date > latest_date:
            latest_version = ver
            latest_date = date

    if latest_version != current_packages[pkg_id]:
        days_diff = (latest_date - current_date).days
        package_info[pkg_id] = {
            "current": current_packages[pkg_id],
            "latest": latest_version,
            "days_outdated": days_diff
        }

# 3. 按过时天数降序排序
sorted_packages = sorted(package_info.items(), key=lambda x: x[1]["days_outdated"], reverse=True)

# 输出优先级列表
print("NuGet包更新优先级(按过时最久排序):")
for pkg_id, info in sorted_packages:
    print(f"{pkg_id}: {info['current']} → {info['latest']} | 过时 {info['days_outdated']} 天")

# 生成更新命令
print("\n执行以下命令完成更新:")
for pkg_id, info in sorted_packages:
    print(f"nuget update {project_path} -Id {pkg_id} -Version {info['latest']}")

三、注意事项

  • 大型企业应用更新前,必须在测试环境验证兼容性,避免引入破坏性变更。
  • 部分包可能未公开发布日期,需调整脚本逻辑处理这类情况。
  • 若需批量处理解决方案内所有项目,可修改脚本遍历所有.csproj文件。

内容的提问来源于stack exchange,提问作者Denis Bredikhin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 09:15:34