我使用Powershell从ftp站点下载新文件

时间:2014-03-31 22:00:48

标签: powershell ftp

我的脚本使用来自ftp站点的数据下载硬编码文件名,但我需要它来下载最新文件(可能是上次下载的时间戳)。我刚开始使用powershell并且已经搜索了线索以使我的脚本更复杂,但似乎无法获得我发现的大部分代码。你能给我一些方向吗?这是我目前的代码:

  # Create FTP Connection
$FTPRequest = [System.Net.FtpWebRequest]::Create("ftp://ftp.sitepath/newestfile.txt") 
$FTPRequest.Credentials = New-Object System.Net.NetworkCredential("username", "pw") 
$FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile

$FTPRequest.UsePassive = $false
$FTPRequest.UseBinary = $true
$FTPRequest.KeepAlive = $false
$folderName = (Get-Date).tostring("dd-MM-yyyy-hh-mm-ss")            
New-Item -itemType Directory -Path \\server\directory\ -Name $FolderName
$targetfile = New-Object  
IO.FileStream "\\server\directory\$FolderName\newestfilename.txt"),        [IO.FileMode]::Create)
# Get FTP File
$FTPResponse = $FTPRequest.GetResponse()
$ResponseStream = $FTPResponse.GetResponseStream()
$FTPReader = New-Object -typename System.IO.StreamReader -ArgumentList $ResponseStream
[byte[]]$readbuffer = New-Object byte[] 1024

#loop through the download stream and send the data to the target file
do{
    $readlength = $ResponseStream.Read($readbuffer,0,1024)
    $targetfile.Write($readbuffer,0,$readlength)
}
while ($readlength -ne 0)
$FTPReader.Close()

$FTPReader.Close()

Thank you for your help.

1 个答案:

答案 0 :(得分:0)

使用Powershell FTP模块(http://gallery.technet.microsoft.com/scriptcenter/PowerShell-FTP-Client-db6fe0cb) - 您可以专注于业务逻辑,而不是让“FTP部分”工作。