Lexxy
Lexxy

Reputation: 477

Copy file from FTP with lastwritetime

How to copy file from ftp with saving original lastwritetime, not current time?

This download file, and set lastwritetime current time.

$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)

Upvotes: 2

Views: 304

Answers (1)

Julien
Julien

Reputation: 447

In order to set the "server last write time", you need to retrieve at the same time as you retrieve the actual file. Once you have both, you can update the local last update time with the time from the server.

Edit: I updated the script to make two requests. The first one is fast as it only retrieves the remote file Timestamp. Once we have it, we download the file to the disk and update the last modified date for the file.

$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,0,1024)
    $LocalFileFile.Write($ReadBuffer,0,$ReadLength)
}
while ($ReadLength -ne 0)
$LocalFileFile.Close()

#Update the Last Modified DateTime
$(Get-Item $LocalFile).LastWriteTime=$RemoteLastModifiedTime

Upvotes: 3

Related Questions