如何使用PowerShell一键下载Nuget包的所有版本?
摘要:一转眼好几年没有写博客了,来博客园冒个泡,最近由于工作需要,内网办公,幸运的是只需要上传一个*.nupkg一个包信息就可以在私有nuget下载到了,下面就用PowerShell编写下载脚本,需要注意的是PowerShell后缀ps1(最后一
一转眼好几年没有写博客了,来博客园冒个泡,最近由于工作需要,内网办公,幸运的是只需要上传一个*.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 projec
