WebClient请求期间发生异常(Powershell)

时间:2018-01-05 18:00:20

标签: powershell

我正在尝试使用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")
            }
         }
      }
   }
}

3 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

在@ Gerald Schneider的答案旁边,请注意,如果客户端进程不需要创建输出文件的权限,也会发生相同的 WebException

我建议您采取以下策略:

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

希望它会有所帮助:-)

答案 2 :(得分:0)

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

相关问题