Copy file and rename existing file

Hello Powershell experts,

I was wondering if you could help me. I am trying to write a script that copies files from a ‘source’ directory to a ‘target’ directory.

What I want to do is, during copy if a file exists with same name but with different time stamp, then rename the existing file in ‘destination’ directory and put the new one in.

Since the copy would be done on daily basis, 90% of the files will be skipped as they have been copied anyways. The challenge is when there is a a file with same name but different time stamp.

How can I achieve this? Code below:

#Set log file location

# "===Start of backup==="

#Script to copy log files
# /e copies subdirectories
# /xo Source directory files older than the destination are excluded from the copy.
# /Out-File will make sure that output will be captured in the logfile. It will be encoded to UTF8 so no special characters appear in the file. -append will ensure that log file does not get 
robocopy $sourcedir $destinationdir /e /xo | Out-File $LogPath\$LogFile -Encoding utf8 -Append

# "===End of backup==="

PO Noob,
Welcome to the forum. :wave:t4:

What problem do you actually try to solve? It sounds like a tinkered backup solution. You may consider a more professional approach. Either with a proper backup software or at least not with an error prone selfmade script.

If the target directory is on a Windows OS you could use Shadow Copies to have different revisions of changed files.

Anyway …

If you’re looking for different time stamp in general - not only older files - you’d need to use the options /xo AND /xn. :wink:

Anyway … since robocopy does not have a switch to rename files you’d need to use another approach. Either you parse the log file you get from robocopy to determine the files you have to treat. Or you use

rightaway on both sides - source and destination - compare the properties you want with

and use the result to skip the copy job for the files already copied and rename and copy the rest accordingly inside of a loop with


Please always read the help for the cmdlets you’re about to use completely including the examples to learn how to use them.