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.
cp command provides an option –p for copying the file without changing the mode, ownership and timestamps. ownership, mode and timestamp. $ cp -p num.
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.
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.
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...)
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())
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With