使用PowerShell下载目录中的所有文件

时间:2015-02-05 18:52:28

标签: powershell ftp

我有一个工作的PowerShell脚本,它遍历通过FTP访问的目录并打印它的内容。脚本如下所示:

$sourceuri = "<string>"
$targetpath = "<string>"
$username = "<string>"
$password = "<string>"

# Create a FTPWebRequest object to handle the connection to the ftp server
$ftprequest = [System.Net.FtpWebRequest]::create($sourceuri)

# set the request's network credentials for an authenticated connection
$ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password)

$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
$ftprequest.UseBinary = $true
$ftprequest.KeepAlive = $false

# send the ftp request to the server
$ftpresponse = $ftprequest.GetResponse()
$stream = $ftpresponse.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 

我的实际目标不仅仅是列出文件,而是将它们下载到运行脚本的机器上。我发现这有点棘手,因为我的循环只引用字节而不是文件名。如何使用此循环下载目录中的所有文件而不是仅列出它们?

2 个答案:

答案 0 :(得分:1)

我更喜欢使用类似winscp的真实FTP库,但还有其他的例子。 http://winscp.net/eng/docs/library_session_listdirectory#example

答案 1 :(得分:-1)

一旦你有一个目录和文件列表 - 使用get-content方法从列表中读取,然后使用位传输来下载所有文件 - 我不确定这是否会下载目录以及...但它肯定会下载文件......