【问题标题】:Error while trying to download Files using Power Shell尝试使用 Powershell 下载文件时出错
【发布时间】:2018-04-02 10:25:34
【问题描述】:

当我尝试从 https URL 下载文件时出现以下错误。我正在使用 Power Shell 3.0

Shell 脚本

$Username = 'user'
$Password = 'password'
$Url = "url"
$Path = "path"
$WebClinet = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.Networkcredential($Username, $Password)
$WebClient.DownloadFile( $Url, $Path )

错误:

使用“2”参数调用“DownloadFile”的异常:“WebClient 请求期间发生异常。” 在行:7 字符:1 + $WebClient.DownloadFile($Url, $Path)

有什么建议吗?

【问题讨论】:

  • 那不是 PowerShell 1.0,请查看$PSVersionTable.PSVersion.ToString() 获取实际版本
  • 我的错!它的 3.0.. 对我描述的错误有什么建议吗?
  • @Dhruv 您为其提供凭据的用户是否具有$Url$Path 的访问权限?

标签: powershell


【解决方案1】:

将现有的 powershell 代码包装在 try catch 块中并写出异常详细信息,以便了解导致问题的实际错误。

Try
{
    $Username = 'user'
    $Password = 'password'
    $Url = "url"
    $Path = "path"
    $WebClient = New-Object System.Net.WebClient
    $WebClient.Credentials = New-Object System.Net.Networkcredential($Username, $Password)
    $WebClient.DownloadFile( $Url, $Path )
}
Catch [Exception]
{
    Write-Host $_.Exception | format-list -force
}

您的代码中还有一个错字。检查你的变量名。

【讨论】:

  • 谢谢! '$Path' 引发访问问题。
  • 如果可能,尝试使用错误消息更新您的问题,以进一步澄清它是否有必要解决您的问题。
  • 这是我得到的错误。但是我正在从同一路径执行 Powershell 脚本并且它具有访问权限。 System.Net.WebException:在 WebClient 请求期间发生异常。 ---> System.UnauthorizedAccessException: 访问路径 '' 被拒绝。
  • 访问问题已修复.. 但现在我收到以下错误 System.Net.WebException:无法解析远程名称:
  • +1 关于如何捕获和写出异常及其堆栈跟踪的评论。我是 PS 和 Windows 的新手,这对找出我的错误非常有帮助。
【解决方案2】:

在脚本中添加了以下命令,现在可以正常工作了

   [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

【讨论】:

    猜你喜欢
    • 2017-05-14
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 2016-06-04
    相关资源
    最近更新 更多