【问题标题】:Only download new files from FTP directory to local folder using PowerShell仅使用 PowerShell 将新文件从 FTP 目录下载到本地文件夹
【发布时间】:2019-03-29 07:54:43
【问题描述】:

我有一个 PowerShell 脚本,它将所有文件从 FTP 目录下载到本地文件夹(感谢 Martin Prikryl)。

FTP 目录会在一天中的不同时间更新多个新文件。

我将通过任务计划程序每 30 分钟运行一次脚本,以从 FTP 目录下载文件。

我希望脚本检查并仅将新文件从 FTP 目录下载到本地文件夹。

注意:必须在 FTP 目录上进行检查,因为之前下载的文件可能会从本地文件夹中删除。

请参阅下面的我当前的脚本;

#FTP Server Information - SET VARIABLES
$user = 'user' 
$pass = 'password'
$target = "C:\Users\Jaz\Desktop\FTPMultiDownload"
#SET FOLDER PATH
$folderPath = "ftp://ftp3.example.com/Jaz/Backup/"

#SET CREDENTIALS
$credentials = new-object System.Net.NetworkCredential($user, $pass)

function Get-FtpDir ($url,$credentials) {
    $request = [Net.WebRequest]::Create($url)
    $request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
    if ($credentials) { $request.Credentials = $credentials }
    $response = $request.GetResponse()
    $reader = New-Object IO.StreamReader $response.GetResponseStream() 
    $reader.ReadToEnd()
    $reader.Close()
    $response.Close()
}

$Allfiles=Get-FTPDir -url $folderPath -credentials $credentials
$files = ($Allfiles -split "`n")

$files 

$webclient = New-Object System.Net.WebClient 
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
$counter = 0
foreach ($file in ($files | where {$_ -like "*.*"})){
    $source=$folderPath + $file
    $destination = Join-Path $target $file
    $webclient.DownloadFile($source, $destination)

    #PRINT FILE NAME AND COUNTER
    $counter++
    $counter
    $source
}

提前感谢您的帮助!

【问题讨论】:

    标签: .net powershell ftp ftpwebrequest


    【解决方案1】:

    在您的循环中,在实际下载之前检查本地文件是否存在:

    $localFilePath = $target + $file
    if (-not (Test-Path $localFilePath))
    {
        $webclient.DownloadFile($source, $localFilePath)
    }    
    

    由于您实际上不保留本地文件,因此您必须记住已在某种日志中下载了哪些文件:

    # Load log
    $logPath = "C:\log\path\log.txt"
    
    if (Test-Path $logPath)
    {
        $log = Get-Content $logPath
    }
    else
    {
        $log = @()
    }
    
    # ... Then later in the loop:
    
    foreach ($file in ($files | where {$_ -like "*.*"})){
        # Do not download if the file is already in the log.
        if ($log -contains $file) { continue }
    
        # If this is a new file, add it to a log and ...
        $log += $file
    
        # ... download it using your code
    }
    
    # Save the log    
    Set-Content -Path $logPath -Value $log
    

    请注意,您将列表拆分为行的代码不是很可靠。如需更好的解决方案,请参阅我对PowerShell FTP download files and subfolders 的回复。


    相关问题:
    Download most recent file from FTP using PowerShell

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 2013-12-29
      • 2017-04-12
      • 2018-11-28
      • 2016-09-02
      • 1970-01-01
      相关资源
      最近更新 更多