PowerShell一鍵下載Nuget某個包的所有版本

丁双磊發表於2024-12-10

一轉眼好幾年沒有寫部落格了,來部落格園冒個泡,最近由於工作需要,內網辦公,幸運的是隻需要上傳一個*.nupkg一個包資訊就可以在私有nuget下載到了,下面就用PowerShell編寫下載指令碼,需要注意的是PowerShell字尾ps1(最後一個數字1),以Newtonsoft.Json為例:

下載地址

# 設定NuGet包列表的URL
$packageName = "Newtonsoft.Json"
$targetHttp = "https://www.nuget.org/packages/"
$targetUrl = "{0}{1}" -f $targetHttp, $packageName

儲存地址

# 設定儲存已下載包的目錄
$outputDirectory = "D:\nuget_packages"
if (-not (Test-Path $outputDirectory)) {
    New-Item -Path $outputDirectory -ItemType Directory
}

解析下載版本地址

定義下載需要解析的包地址

# 定義下載字首
$httpPrefix = "https://www.nuget.org/api/v2/package/"
# 下載html檔案內容
$htmlContent = Invoke-WebRequest -Uri $targetUrl -UseBasicParsing | Select-Object -ExpandProperty Content
# 匹配標籤
$pattern = "<.*?>"
$matches = [regex]::Matches($htmlContent, $pattern)

獲取所有a標籤

foreach ($match in $matches) {
  $tag = $match.Value
  # 獲取a標籤
  if ($tag -like "<a href=*") {
    Write-Host $tag
  }
}

輸出結果

<a href="#" id="skipToContent" class="showOnFocus" title="Skip To Content">
...
<a href="/packages/System.Xml.XmlDocument/">
<a href="/packages/Newtonsoft.Json/13.0.3" title="13.0.3">
...
<a href="/packages/Newtonsoft.Json/3.5.8" title="3.5.8">
<a href="/stats/packages/Newtonsoft.Json?groupby=Version" title="Package Statistics">
...
<a href="/packages/Newtonsoft.Json/13.0.3/ReportAbuse" title="Report the package as abusive">
<a href="/packages/Newtonsoft.Json/13.0.3/ContactOwners" title="Ask the package owners a question">
...

觀察上一步結果可以看出來每一個版本都有title,且title內容是版本

# 獲取含有title的a標籤
if ($tag -like "*title=*") {
  Write-Host $tag        
}

輸出結果

<a href="#" id="skipToContent" class="showOnFocus" title="Skip To Content">
<a href="/packages/Newtonsoft.Json/13.0.3" title="13.0.3">
...
<a href="/packages/Newtonsoft.Json/3.5.8" title="3.5.8">
<a href="/stats/packages/Newtonsoft.Json?groupby=Version" title="Package Statistics">
<a href="https://www.newtonsoft.com/json" data-track="outbound-project-url" title="Visit the project site to learn more about this package" rel="nofollow">
...
<a href="/packages/Newtonsoft.Json/13.0.3/ReportAbuse" title="Report the package as abusive"> <a href="/packages/Newtonsoft.Json/13.0.3/ContactOwners" title="Ask the package owners a question"> <a href="/packages?q=Tags%3A%22json%22" title="Search for json" class="tag">

接著上一步的結果繼續過濾

# 擷取href的內容
$substr = $tag.Substring(9)
if ($substr -like "/packages/*") {
    Write-Host $substr
}

輸出結果

/packages/Newtonsoft.Json/13.0.3" title="13.0.3">
...
/packages/Newtonsoft.Json/3.5.8" title="3.5.8">
/packages/Newtonsoft.Json/13.0.3/ReportAbuse" title="Report the package as abusive">
/packages/Newtonsoft.Json/13.0.3/ContactOwners" title="Ask the package owners a question">

有完沒完,又來了?看上面的結果就還差過濾兩個不相關的了,

獲取href完整內容

# 查詢第一個雙引號的位置
$index = $substr.IndexOf('"')
# 獲取部分/packages/Newtonsoft.Json/13.0.3
$substr = $substr.Substring(0,$index)

剔除最後兩個版本無關的a標籤

# 排除報告濫用a標籤
if ($substr -notlike "*/ReportAbuse") {   # 排除聯絡作者a標籤   if ($substr -notlike "*/ContactOwners") {     # 匹配版本
    $endIndex = $substr.LastIndexOf('/')     $startPackageIndex = $endIndex + 1     $packageVersion = $substr.Substring($startPackageIndex)   } }

Invoke-WebRequest命令下載並儲存檔案

# 下載地址nupkg
$packageUrl = "{0}{1}/{2}" -f $httpPrefix,$packageName,$packageVersion # 生成儲存檔案的路徑 $packageFile = Join-Path -Path $outputDirectory -ChildPath "$packageName.$packageVersion.nupkg" # 下載 .nupkg 檔案 Write-Host "Downloading $packageName version $packageVersion from $packageUrl" Invoke-WebRequest -Uri $packageUrl -OutFile $packageFile

全部程式碼

PowerShell一鍵下載Nuget某個包的所有版本
# 設定NuGet包列表的URL
$packageName = "Newtonsoft.Json"
$targetHttp = "https://www.nuget.org/packages/"
$targetUrl = "{0}{1}" -f $targetHttp, $packageName
# 設定儲存已下載包的目錄
$outputDirectory = "D:\nuget_packages"
if (-not (Test-Path $outputDirectory)) {
    New-Item -Path $outputDirectory -ItemType Directory
}
# 定義下載字首
$httpPrefix = "https://www.nuget.org/api/v2/package/"
# 下載html檔案內容
$htmlContent = Invoke-WebRequest -Uri $targetUrl -UseBasicParsing | Select-Object -ExpandProperty Content
# 匹配標籤
$pattern = "<.*?>"
$matches = [regex]::Matches($htmlContent, $pattern)
foreach ($match in $matches) {
    $tag = $match.Value
        # 獲取a標籤
        if ($tag -like "<a href=*") {
            # 獲取含有title的a標籤
            if ($tag -like "*title=*")
            {
                # 擷取href的內容
                $substr = $tag.Substring(9)
                if ($substr -like "/packages/*")
                {
                    # 查詢第一個雙引號的位置
                    $index = $substr.IndexOf('"')
                    # 獲取部分/packages/Newtonsoft.Json/13.0.3
                    $substr = $substr.Substring(0,$index)
                    # 排除報告濫用a標籤
                    if ($substr -notlike "*/ReportAbuse")
                    {
                        # 排除聯絡作者a標籤
                        if ($substr -notlike "*/ContactOwners")
                        {
                            # 匹配版本
                            $endIndex = $substr.LastIndexOf('/')
                            $startPackageIndex = $endIndex + 1
                            $packageVersion = $substr.Substring($startPackageIndex)
                            # 下載地址nupkg
                            $packageUrl = "{0}{1}/{2}" -f $httpPrefix,$packageName,$packageVersion
                            # 生成儲存檔案的路徑
                            $packageFile = Join-Path -Path $outputDirectory -ChildPath "$packageName.$packageVersion.nupkg"
                            # 下載 .nupkg 檔案
                            Write-Host "Downloading $packageName version $packageVersion from $packageUrl"
              Invoke-WebRequest -Uri $packageUrl -OutFile $packageFile
                            
                        }
                        
                    }
                    
                }
                
            }
            
        }
}
# 執行結束暫停
$null = Read-Host
View Code

相關文章