Last active
April 1, 2023 15:39
-
-
Save rfennell/835575c96f54e27a3ba0816f2f8c2317 to your computer and use it in GitHub Desktop.
Downloading NuGet packages with 'System.Net.WebClient' from an Azure DevOps Artifact feed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param( | |
$package, | |
$version, | |
$azdoOrg, | |
$feedname, | |
# provide a, Azure DevOps PAT if it a private feed | |
$pat, | |
$DestinationPath = "$package-$version.zip" | |
) | |
# URI format for PowerShell gallery is simply | |
# $uri = "https://www.powershellgallery.com/packages/$package/$version" | |
# URI format for PowerShell gallery is more complex | |
$parsedversion = [Version]::Parse($version) | |
$uri= "https://pkgs.dev.azure.com/$azdoOrg/_packaging/$feedName/nuget/v2?id=$($package.ToLower())&version=$($parsedversion.major).$($parsedversion.minor).$($parsedversion.build)" | |
[System.Net.WebClient] $webClient = New-Object -TypeName 'System.Net.WebClient'; | |
$webClient.Headers.Add('user-agent', $labDefaults.ModuleName); | |
$BufferSize = 1MB | |
if ($pat) { | |
$feedPasword = ConvertTo-SecureString -String $pat -AsPlainText -Force | |
$Credential = New-Object System.Management.Automation.PSCredential ('AzureDevOps', $feedPasword) | |
$webClient.Credentials = $Credential; | |
} | |
[System.IO.Stream] $inputStream = $webClient.OpenRead($Uri); | |
[System.UInt64] $contentLength = $webClient.ResponseHeaders['Content-Length']; | |
$path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($DestinationPath); | |
[System.IO.Stream] $outputStream = [System.IO.File]::Create($path); | |
[System.Byte[]] $buffer = New-Object -TypeName System.Byte[] -ArgumentList $BufferSize; | |
[System.UInt64] $bytesRead = 0; | |
[System.UInt64] $totalBytes = 0; | |
$writeProgessActivity = $localized.DownloadingActivity -f $Uri; | |
do { | |
$iteration ++; | |
$bytesRead = $inputStream.Read($buffer, 0, $buffer.Length); | |
$totalBytes += $bytesRead; | |
$outputStream.Write($buffer, 0, $bytesRead); | |
## Avoid divide by zero | |
if ($contentLength -gt 0) { | |
if ($iteration % 30 -eq 0) { | |
[System.Byte] $percentComplete = ($totalBytes / $contentLength) * 100; | |
$writeProgressParams = @{ | |
Activity = $writeProgessActivity; | |
PercentComplete = $percentComplete; | |
Status = $localized.DownloadStatus -f $totalBytes, $contentLength, $percentComplete; | |
} | |
Write-Progress @writeProgressParams; | |
} | |
} | |
} | |
while ($bytesRead -ne 0) | |
$outputStream.Close(); | |
Get-Item -Path $path; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment