使用基本身份验证的 Powershell 下载文件

标签 powershell

我正在尝试使用 PowerShell 从我的 JFrog 存储库中下载一个文件,但我无法让它工作。

这是我得到的错误:

Exception calling "DownloadFile" with "2" argument(s): "The underlying connection was closed: An unexpected error
occurred on a send."
At     C:\Users\jelte\Documents\myproject\downloadExecutables1.ps1:16 char:1
+ $req.DownloadFile('https://myrepo.jfrog.io/myproject/libs-release-loca ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], 

MethodInvocationException

The code I use:

$usernameVar = "JFROG_USERNAME"
$username = (get-item env:$usernameVar).Value

$passwordVar = "JFROG_PASSWORD"
$password = (get-item env:$passwordVar).Value

$auth = 'Basic ' + [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($username+":"+$password))
$req = New-Object System.Net.WebClient
$req.Headers.Add('Authorization', $auth)
$installersFolder = $PSScriptRoot + '\prerequisites\executables'
If(!(test-path $installersFolder))
{
      New-Item -ItemType Directory -Force -Path $installersFolder
}

$req.DownloadFile('https://myrepo.jfrog.io/myproject/libs-release-local/binary/com/targetexecutable/9.3.240/executable-9.3.240.exe', $installersFolder + '\executable-9.3.240.exe')

我尝试过的事情:
  • 从不安全的服务器下载文件,这是可行的。我怀疑基本身份验证出了点问题。
  • 我检查了用户名和密码是否填写,我还检查了 base64 哈希是否正确。
  • 将 PowerShell 置于跟踪模式,这样我就可以得到更清晰的错误,但运气不好。 (为什么这些错误如此不清楚?)
  • 使用 Invoke-Webrequest ,这可行,但速度极慢。
  • 使用 cURL 检查它是否是其他东西,这也有效。
  • 最佳答案

    尝试将这些行添加到脚本的开头。

    $AllProtocols = [System.Net.SecurityProtocolType]'Tls12'
    [System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols 
    

    我在没有非常丰富的错误消息的情况下遇到了类似的情况,问题显然只是我需要将 powershell 使用的安全协议(protocol)设置为 Tls 1.2。

    关于使用基本身份验证的 Powershell 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51148286/

    相关文章:

    powershell - 如何让 Get-ChildItem 处理带有不间断空格的路径

    arrays - 用于将元素添加到数组的PowerShell函数

    powershell - 使用Powershell在Exchange 2013中确定Exchange Server版本

    xml - Powershell:如何选择和修改Xml注释?

    loops - Powershell $Host.UI.ReadKey() 菜单循环 - 按键未重置

    powershell - Powershell删除文件名开头和结尾的特定字符

    windows - 如何通过 Powershell 和 PSSessionConfiguration 远程连接到 Exchange 服务器

    php - 在 wamp 2.5 上安装 zend Framework 2 时出现问题

    powershell - 是否可以将代码部署到 Azure 云服务而无需构建步骤?

    winforms - Powershell将文本框作为函数参数传递