How to copy only updated or newer files with 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. This would be tricky because we need to write several lines of code for it.

But Windows support xCopy utility which can directly copy the newer or updated files and this utility we can accommodate in PowerShell as well.

xCopy uses a switch called /d. its actual syntax is,

Syntax

/d [:MM-DD-YYYY]

This means if the date specified, it copies the files and folders newer than that date and if don't specify any date then it copies all files and folders that are updated. An example is shown below.

Source:

C:\DSC

Destination:

E\Temp

Our folder structure is like this, LabMachine2k16.mof file also exists on the destination but it is an updated file, Test.txt is a new file and the Pagefile folder is a new folder but it is an empty one.

Example

xcopy C:\DSC E:\Temp\ /s /d /e /f /y

Output

PS C:\> xcopy C:\DSC E:\Temp\ /s /d /e /f /y
C:\DSC\LabMachine2k16.mof -> E:\Temp\LabMachine2k16.mof
C:\DSC\Test.txt -> E:\Temp\Test.txt
2 File(s) copied

Switches.

/s – Specifies the subfolder

/e – Specifies the empty directory

/d – Specifies the updated files to copy

/f – Displays the source and the destination.

/y – Confirms without asking user prompt.

Updated on: 18-Mar-2021

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements