PowerShell DownloadFile()不适用于Nexus工件下载

时间:2017-10-16 17:22:57

标签: powershell webclient downloadfile

我正在尝试从Nexus存储库下载最新的工件。如果我给出确切的zip文件名,它工作正常。当我尝试使用通用URL(REST URI)下载时,它给我401 Unauthorized。我也尝试了Invoke-WebRequestWebClientInvoke-RestMethod

$wc = New-Object System.Net.WebClient
$URL = "http://nexusrepo/nexus/service/local/artifact/maven/redirect?r=my-snapshot&g=my.group.id&a=my.artifact.id&v=1.10.0-SNAPSHOT&c=win32.win32.x86_64&p=zip"
$username = "nexus"
$password = "nexus"
$auth = $username + ":" + $password
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
$Encoded = [System.Text.Encoding]::UTF8.GetBytes($auth)
$EncodedPassword = [System.Convert]::ToBase64String($Encoded)
$wc.Headers.Add("Accept-Encoding", "gzip,deflate")
$wc.Credentials = New-Object System.Net.NetworkCredential($username, $password)
$wc.Headers.Add("Authorization", "Basic " + $EncodedPassword)
$wc.UseDefaultCredentials = $false
$wc.DownloadFile($URL, "MyApp.zip")
Exception calling "DownloadString" with "1" argument(s): "The remote server
returned an error: (401) Unauthorized."
At C:\temp\NexusDownloadTest\Nexus-Download.ps1:39 char:1
+ $weburl = $wc.DownloadString($URL)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

作为一种解决方法,我回到Invoke-WebRequest并首先使用MaximumRedirection 0获取重定向的URL,然后将该URL作为请求提交。以下代码有效。

$URL = "http://nexusrepo/nexus/service/local/artifact/maven/redirect?r=my-snapshot&g=my.group.id&a=my.artifact.id&v=1.10.0-SNAPSHOT&c=win32.win32.x86_64&p=zip"
$username = "nexus"
$password = "nexus"
$auth=$username+":"+$password
$Encoded = [System.Text.Encoding]::UTF8.GetBytes($auth)
$EncodedPassword = [System.Convert]::ToBase64String($Encoded)
$latestArtifactURL = Invoke-WebRequest $url -Headers @{Authorization = "Basic $EncodedPassword"} -MaximumRedirection 0
$redirectedMessage = "$latestArtifactURL".IndexOf('http:')
$targetURL = "$latestArtifactURL".SubString("$redirectedMessage") 
Invoke-WebRequest $targetURL -Headers @{Authorization = "Basic $EncodedPassword"} -OutFile "MyApp.zip"