问题描述
如何从ftp复制文件并保存原始的lastwritetime,而不是当前时间?
此下载文件,并设置lastwritetime当前时间。
$Login = 'anonymous'
$Pass = ''
$url = "ftp://ftp.intel.com/readme.txt"
$local = "C:\docs\readme.txt"
$WC = new-object System.Net.WebClient
$WC.Credentials = [Net.NetworkCredential]::new($Login,$Pass)
$WC.downloadFile($url,$local)
解决方法
为了设置“服务器上次写入时间”,您需要在检索实际文件的同时进行检索。 两者都完成后,您可以使用服务器中的时间来更新本地上次更新时间。
编辑:我更新了脚本以发出两个请求。第一个很快,因为它只检索远程文件Timestamp。有了它后,我们将文件下载到磁盘并更新文件的最后修改日期。
$LocalFile = "c:\temp\readme2.txt"
$url = "ftp://ftp.intel.com/readme.txt"
#Retrieve the DateTimestamp of the remote file
$WR = [Net.WebRequest]::Create($url)
$WR.Method = [Net.WebRequestMethods+FTP]::GetDateTimestamp
$WR.Credentials = [Net.NetworkCredential]::new("anonymous","")
$Response = $WR.GetResponse()
$RemoteLastModifiedTime = $Response.LastModified
#Retrieve the file content
$WR1 = [Net.WebRequest]::Create($url)
$WR1.Method = [Net.WebRequestMethods+FTP]::DownloadFile
$WR1.Credentials = [Net.NetworkCredential]::new("anonymous","")
$Response1 = $WR1.GetResponse()
$ResponseStream = $Response1.GetResponseStream()
# Create the target file on the local system and the download buffer
$LocalFileFile = New-Object IO.FileStream ($LocalFile,[IO.FileMode]::Create)
[byte[]]$ReadBuffer = New-Object byte[] 1024
# Loop through the download
do {
$ReadLength = $ResponseStream.Read($ReadBuffer,1024)
$LocalFileFile.Write($ReadBuffer,$ReadLength)
}
while ($ReadLength -ne 0)
$LocalFileFile.Close()
#Update the Last Modified DateTime
$(Get-Item $LocalFile).LastWriteTime=$RemoteLastModifiedTime