【问题标题】:An exception occurred during a WebClient request (Powershell)WebClient 请求期间发生异常 (Powershell)
【发布时间】:2020-12-23 21:36:20
【问题描述】:

我正在尝试使用 Powershell 从我们的 HTTP 服务器复制一个目录文件夹,我想将它的全部内容(包括子文件夹)复制到我当前服务器的本地驱动器中。这样做的目的是为了服务器部署自动化,这样我的老板就可以运行我的 powershell 脚本并进行整个服务器设置,并将我们所有的文件夹复制到它的 C: 驱动器。这是我的代码

$source = "http://servername/serverupdates/deploy/Program%20Files/"
$destination = "C:\Program Files"
$client = new-object System.Net.WebClient
$client.DownloadFile($source, $destination)

当我以管理员身份在 Powershell ISE 中运行脚本时,我收到错误消息

“使用“2”个参数调用“DownloadFile”的异常:“WebClient 请求期间发生异常。”

对可能发生的事情有什么建议吗?

我也试过这个代码块,但是当我运行它时没有任何反应,没有错误或任何东西。

$source = "http://serverName/serverupdates/deploy/Program%20Files/"
$webclient = New-Object system.net.webclient
$destination = "c:/users/administrator/desktop/test/"


Function Copy-Folder([string]$source, [string]$destination, [bool]$recursive) {
    if (!$(Test-Path($destination))) {
    New-Item $destination -type directory -Force
}

# Get the file list from the web page
$webString = $webClient.DownloadString($source)
$lines = [Regex]::Split($webString, "<br>")
# Parse each line, looking for files and folders
foreach ($line in $lines) {
    if ($line.ToUpper().Contains("HREF")) {
        # File or Folder
        if (!$line.ToUpper().Contains("[TO PARENT DIRECTORY]")) {
            # Not Parent Folder entry
            $items =[Regex]::Split($line, """")
            $items = [Regex]::Split($items[2], "(>|<)")
            $item = $items[2]
            if ($line.ToLower().Contains("&lt;dir&gt")) {
                # Folder
                if ($recursive) {
                    # Subfolder copy required
                    Copy-Folder "$source$item/" "$destination$item/" $recursive
                } else {
                    # Subfolder copy not required
                }
            } else {
                # File
                $webClient.DownloadFile("$source$item", "$destination$item")
            }
         }
      }
   }
}

【问题讨论】:

    标签: powershell


    【解决方案1】:

    System.Net.WebClient.DownloadFile 期望第二个参数是文件名,而不是目录。不能递归下载目录,只能下载单个文件。

    对于第二部分,逐行运行,看看会发生什么。但是解析HTML获取路径容易出错,是generally advised against

    我的建议:不要为此使用 http。从文件共享中复制内容,只需一行,为您省去很多麻烦。如果必须使用 http,请下载一个存档并将其解压缩到目标目录中。

    【讨论】:

    • 我尝试这样做的唯一原因是,如果我使用 IP 地址使用 Robocopy,它将完全按照我的意愿执行,但我必须先打开 Windows 资源管理器并 \\ 进入IP地址,以便我登录服务器。感谢您的帮助,我认为问题在于它不是文件。
    【解决方案2】:

    除了@Gerald Schneider 的回答,请注意如果客户端进程没有创建输出文件所需的权限,也可能会发生相同的WebException

    我建议你采取以下策略:

    1. 将文件下载为具有 .tmp (.txt) 扩展名的唯一文件名 Windows 临时文件夹以避免写入权限和其他权限问题
    2. 将临时文件移动到目标文件夹
    3. 将临时文件重命名为目标文件名

    希望对你有帮助:-)

    【讨论】:

      【解决方案3】:

      除了其他答案之外,如果您的磁盘空间不足,可能会发生错误。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多