2011-08-13 44 views
6

我想做一個ftp目錄的列表視圖。到目前爲止,查看部分是確定的,但我無法操縱我回來的數據。這是我使用的腳本;powershell:ftp目錄列表(幫助腳本)

[System.Net.FtpWebRequest]$ftp = [System.Net.WebRequest]::Create("ftp://ftp.microsoft.com/ResKit/y2kfix/alpha/") 
$ftp.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory #Details 

$response = $ftp.getresponse() 
$stream = $response.getresponsestream() 

$buffer = new-object System.Byte[] 1024 
$encoding = new-object System.Text.AsciiEncoding 

$outputBuffer = "" 
$foundMore = $false 

## Read all the data available from the stream, writing it to the 
## output buffer when done. 
do 
{ 
    ## Allow data to buffer for a bit 
    start-sleep -m 1000 

    ## Read what data is available 
    $foundmore = $false 
    $stream.ReadTimeout = 1000 

    do 
    { 
     try 
     { 
      $read = $stream.Read($buffer, 0, 1024) 

      if($read -gt 0) 
      { 
       $foundmore = $true 
       $outputBuffer += ($encoding.GetString($buffer, 0, $read)) 
      } 
     } catch { $foundMore = $false; $read = 0 } 
    } while($read -gt 0) 
} while($foundmore) 

$outputBuffer 

這是我爲此腳本創建的響應;

PS C:\Users\Toshiba> C:\Apps\@PowerShell\FTPListDirectory.ps1 
forfiles.exe 
logtime.exe 
timeserv 
w32time 

從那裏,我可以如何處理我回來的數據。文件信息(名稱,創建時間,上次更新等)和其他內容。

我的目標是查看目錄中的所有ftp數據,然後我可以下載目錄中的所有文件。

有沒有機會?

回答

8

首先,你應該檢索所有數據

與此

$ftp.Method = [System.Net.WebRequestMethods+FTP]::ListDirectoryDetails 

更換方法沒有細節,你只得到文件名。

要下載文件我通常使用WebClient類

$webclient = New-Object System.Net.WebClient 
$webclient.credentials = New-Object System.Net.NetworkCredential("anonymous","[email protected]") 
$webclient.downloadfile("ftp://ftp.host.com/file.txt", "c:\temp\file.txt") 

Downloadfile method of the webclient class