2012-07-11 24 views
4

我可以使用從網上下載一個文件:如何從網上下載文件/子文件夾的整個文件夾在PowerShell中

$wc = New-Object System.Net.WebClient 
$wc.DownloadFile("http://blah/root/somefile.ext", "C:\Downloads\www\blah\root\somefile.ext") 

但是我怎麼下載的所有文件,包括子文件夾?像下面的內容將是不錯...

$wc.DownloadFile("http://blah/root/", "C:\Downloads\www\blah\root\") 

本身表現爲IE目錄列表的根文件夾,你知道,像:

[To Parent Directory] 
       01 July 2012 09:00  1234 somefile.ext 
       01 July 2012 09:01  1234 someotherfile.ext 

作爲獎勵,我怎麼會只下載根文件夾中的文件忽略子文件夾?

+0

我認爲這不會被您的網絡服務器支持。只有單個文件的URI才能用於GET。因此,認爲您的解決方案需要兩部分:1)將目錄列表下載爲HTML並解析文件URL 2)分別下載。 – 2012-07-12 08:46:29

回答

4

這就是我想出了基於安迪的建議(用大量的來自谷歌的幫助,當然):

#################################################################################################### 
# This function copies a folder (and optionally, its subfolders) 
# 
# When copying subfolders it calls itself recursively 
# 
# Requires WebClient object $webClient defined, e.g. $webClient = New-Object System.Net.WebClient 
# 
# Parameters: 
# $source  - The url of folder to copy, with trailing /, e.g. http://website/folder/structure/ 
# $destination - The folder to copy $source to, with trailing \ e.g. D:\CopyOfStructure\ 
# $recursive - True if subfolders of $source are also to be copied or False to ignore subfolders 
# Return  - None 
#################################################################################################### 
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") 
       } 
      } 
     } 
    } 
} 

當然不能保證,但它的工作的網站,我在

感興趣
+0

似乎這將節省大量的時間。你可以添加一個這個函數的用法的例子嗎? – 2017-08-25 10:53:48

相關問題