2016-11-28 72 views
5

我正在使用PowerShell腳本,它將從FTP站點提取文件。這些文件每小時上傳到FTP站點,因此我需要下載最新的文件。我目前的代碼下載了今天的所有文件,而不僅僅是一個文件。我如何只下載最新的文件?使用PowerShell從FTP下載最新文件

這裏是我目前正在使用

$ftpPath = 'ftp://***.***.*.*' 
$ftpUser = '******' 
$ftpPass = '******' 
$localPath = 'C:\Temp' 
$Date = get-date -Format "ddMMyyyy" 
$Files = 'File1', 'File2' 

function Get-FtpDir ($url, $credentials) 
{ 
    $request = [Net.FtpWebRequest]::Create($url) 
    if ($credentials) { $request.Credentials = $credentials } 
    $request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory 
    (New-Object IO.StreamReader $request.GetResponse().GetResponseStream()) -split "`r`n" 

} 

$webclient = New-Object System.Net.WebClient 
$webclient.Credentials = New-Object System.Net.NetworkCredential($ftpUser,$ftpPass) 
$webclient.BaseAddress = $ftpPath 

Foreach ($item in $Files) 
{ 
    Get-FTPDir $ftpPath $webclient.Credentials | 
     ? { $_ -Like $item+$Date+'*' } | 
     % { 

      $webClient.DownloadFile($_, (Join-Path $localPath $_)) 
     } 
} 

回答

8

這並不容易與FtpWebRequest的代碼。爲了您的任務,您需要知道文件時間戳。

不幸的是,使用FtpWebRequest/.NET framework/PowerShell提供的功能檢索時間戳沒有真正可靠和有效的方法,因爲它們不支持FTP MLSD命令。命令MLSD以標準化的機器可讀格式提供遠程目錄的列表。命令和格式由RFC 3659標準化。

替代,您可以使用,由.NET框架支持:

  • ListDirectoryDetails法(FTP LIST命令)來檢索目錄中的所有文件的詳細信息,然後您處理FTP服務器特定的格式的細節(* nix格式類似於ls * nix命令是最常見的,缺點是格式可能會隨時間而改變,對於較新的文件「May 8 17:48」格式和較老的文件使用格式「Oct 18 2009 「使用格式)
  • GetDateTimestamp方法(FTP MDTM命令)單獨ret爲每個文件創建時間戳。優點是響應標準化爲RFC 3659YYYYMMDDHHMMSS[.sss]。缺點是你必須爲每個文件發送一個單獨的請求,效率很低。

一些參考:


另外,使用支持MLSD命令第三方FTP圖書館, nd /或支持專有列表格式的解析。例如,WinSCP .NET assembly支持兩者。

一個例子的代碼:

# Load WinSCP .NET assembly 
Add-Type -Path "WinSCPnet.dll" 

# Setup session options 
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{ 
    Protocol = [WinSCP.Protocol]::Ftp 
    HostName = "example.com" 
    UserName = "user" 
    Password = "mypassword" 
} 

$session = New-Object WinSCP.Session 

# Connect 
$session.Open($sessionOptions) 

# Get list of files in the directory 
$directoryInfo = $session.ListDirectory($remotePath) 

# Select the most recent file 
$latest = 
    $directoryInfo.Files | 
    Where-Object { -Not $_.IsDirectory } | 
    Sort-Object LastWriteTime -Descending | 
    Select-Object -First 1 

# Any file at all? 
if ($latest -eq $Null) 
{ 
    Write-Host "No file found" 
    exit 1 
} 

# Download the selected file 
$sourcePath = [WinSCP.RemotePath]::EscapeFileMask($remotePath + $latest.Name) 
$session.GetFiles($sourcePath, $localPath).Check() 

對於一個完整的碼,參見Downloading the most recent file (PowerShell)

(我的WinSCP的作者)

+2

的WinSCP是一個非常實用和非常可靠的:) – Jimbo

+1

WinSCP賦予岩石。使用PowerShell進行FTP傳輸非常高效。 – sodawillow