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



我正试图从Nexus存储库下载最新的工件。如果我给出确切的zip文件名,它就可以正常工作。当我尝试使用通用URL(REST URI)下载时,它会给我401未授权。我也试过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")
使用"1"参数调用"DownloadString"时发生异常:"远程服务器返回错误:(401)未经授权。"在C:\temp\NexusDownloadTest\Nexus Download.ps1:39 char:1+$weburl=$wc.DownloadString($URL)+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+CategoryInfo:未指定:(:)[],MethodInvocationException+FullyQualifiedErrorId:WebException

有人能帮我吗?

作为一种变通方法,我回到InvokeWebRequest,首先使用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"

最新更新