Keep a backup before copying the new files in designation folder

I am trying to create a script to compare the the files between source folder and the destination folder and I have achieved this with the given code. But before copying files from the source to the destination folder, I want to keep a copy of the destination folder. Can anyone please help to modify the codes?

`$Sourcefolder = “C:\Users\parveen.kumar\Downloads\Source”
$Destfolder = “C:\Users\parveen.kumar\Downloads\desi”
$BackupofDestfolder = “C:\Users\parveen.kumar\Downloads\just”

Get-ChildItem -Path $Sourcefolder -File | ForEach-Object {
$existingFile = Get-Item -Path (Join-Path -Path $Destfolder -ChildPath $.Name) -ErrorAction SilentlyContinue
if (!$existingFile -or $existingFile.LastWriteTime -lt $
.LastWriteTime) {
$_ | Copy-Item -Destination $Destfolder -Force
}
} `

Not sure I really understand your logic … but you should be able to get all this done with Robocopy. No need to re-invent the wheel.

2 Likes

Parveen,
Welcome to the forum. :wave:t4:

I’d recommend to use the shadow copy service to keep older version of files you update or replace with newer versions. No need to re-invent the wheel again. :wink:

Regardless of that … when you post code, sample data, console output or error messages please format it as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.

Thanks in advance

How to format code in PowerShell.org <---- Click :point_up_2:t4: :wink:

With the given code, i can fulfill my requirment

$Sourcefolder = "C:\Users\parveen.kumar\Downloads\Source"
$Destfolder   = "C:\Users\parveen.kumar\Downloads\desi"
$BackupofDestfolder   = "C:\Users\parveen.kumar\Downloads\just"


Get-ChildItem -Path $Sourcefolder -File | ForEach-Object {

    $existingFile = Get-Item -Path (Join-Path -Path $Destfolder -ChildPath $_.Name) -ErrorAction SilentlyContinue

    if ($existingFile -and $existingFile.LastWriteTime -lt $_.LastWriteTime) {

            $existingFile | Move-Item -Destination $BackupofDestfolder -Force

        $_ | Copy-Item -Destination $Destfolder -Force

    }

    elseif (!$existingFile) {

        $_ | Copy-Item -Destination $Destfolder -Force

    }
}

Daer All, Please ignore this topic now. I have identified the solution for this requirement.