![](/img/trans.png)
[英]Download files from FTP server in C# to local folder with modification date greater than specified
[英]Only download new files from FTP directory to local folder using PowerShell
我有一個 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
}
在此先感謝您的幫助!
在您的循環中,在實際下載之前檢查本地文件是否存在:
$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 下載文件和子文件夾的回答。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.