Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use powershell to copy file and retain original timestamp

I would like to copy some files or a folder of files from one file server to another. However, I want to keep the original timestamp and file attributes so that the newly copied files will have the same timestamp of the original files. Thanks in advance on any answer.

like image 815
user3277911 Avatar asked Feb 06 '14 03:02

user3277911


People also ask

How do I copy files without changing the timestamp?

cp command provides an option –p for copying the file without changing the mode, ownership and timestamps. ownership, mode and timestamp. $ cp -p num.

How do I copy a directory and preserve a timestamp?

Use the backup function in a tool called xyplorer. Basically when you "backup" a directory of files from drive to another drive, it preserves timestamps for files and directories.

How do I copy only the latest or updated files in PowerShell?

To copy only updated or newer files with PowerShell, we can use Copy-Item with some logic in the script that to check if the files exist on the destination folder if not then copy that file and if yes then compare the timestamp and copy the latest file.


2 Answers

Here's a powershell function that'll do what you're asking... It does absolutely no sanity checking, so caveat emptor...

function Copy-FileWithTimestamp {
[cmdletbinding()]
param(
    [Parameter(Mandatory=$true,Position=0)][string]$Path,
    [Parameter(Mandatory=$true,Position=1)][string]$Destination
)

    $origLastWriteTime = ( Get-ChildItem $Path ).LastWriteTime
    Copy-Item -Path $Path -Destination $Destination
    (Get-ChildItem $Destination).LastWriteTime = $origLastWriteTime
}

Once you've run loaded that, you can do something like:

Copy-FileWithTimestamp foo bar

(you can also name it something shorter, but with tab completion, not that big of a deal...)

like image 99
Hunter Eidson Avatar answered Oct 07 '22 01:10

Hunter Eidson


Here is how you can copy over the time stamps, attributes, and permissions.

$srcpath = 'C:\somepath'
$dstpath = 'C:\anotherpath'
$files = gci $srcpath

foreach ($srcfile in $files) {
  # Build destination file path
  $dstfile = [io.FileInfo]($dstpath, '\', $srcfile.name -join '')

  # Copy the file
  cp $srcfile.FullName $dstfile.FullName

  # Make sure file was copied and exists before copying over properties/attributes
  if ($dstfile.Exists) {
    $dstfile.CreationTime = $srcfile.CreationTime
    $dstfile.LastAccessTime = $srcfile.LastAccessTime
    $dstfile.LastWriteTime = $srcfile.LastWriteTime
    $dstfile.Attributes = $srcfile.Attributes
    $dstfile.SetAccessControl($srcfile.GetAccessControl())
  }
}
like image 24
coffeemak3r Avatar answered Oct 06 '22 23:10

coffeemak3r