Share via

Looking for help with a PowerShell script to back up files that would otherwise be deleted when using Robocopy to mirror folders across PCs

Soeroah Myrddin 0 Reputation points
2024-08-20T10:14:19.1966667+00:00

Hi,

Long story short: I've got a main PC with working files I want to back up to a laptop once a month. There's a lot of files, and sometimes I go in and change the names, or metadata, of files, which causes the folders to become desynchronised when it comes to Indexing and searching.

I've got a Robocopy string that allows me to mirror my PC's folder to my Laptop's folder. However, this does mean if a file has been removed on the PC it will delete that file on the Laptop - this IS what I want, but rather than deleting the file I'd rather it be moved into a third folder so I can audit the logs and make sure I didn't accidentally lose anything.

I've got a string that'll get Robocopy to print a list of files that would be deleted if I ran my main script, so I've got the ability to see what will be deleted. The only problem is getting the PowerShell script to move files that'd otherwise be deleted to work.

Someone previously gave me this code, based on my test folders:

So I've got three relevant folders I need to manage: the Source folder, where my main files are, the Destination folder, where I want to clone my Source folder to, and the Backup folder, where I want extra files in Destination but not in Source to be moved to. Call them Folder 1, Folder 2 and Folder 3 respectively. I've tried editing the script to this, but it didn't do anything:

$source = "C:\Users\David\OneDrive\Desktop\Test 1" $destination = "C:\Users\David\OneDrive\Desktop\Test 2" $backup = "C:\Users\David\OneDrive\Desktop\Test 3" $files = Get-ChildItem -Path $source -Recurse foreach ($file in $files) { $relativePath = $file.FullName.Substring($source.Length + 1) if (-not (Test-Path "C:\Users\David\OneDrive\Desktop\Test 1")) { Move-Item -Path $file.FullName -Destination $backup } }

Running this code doesn't seem to work. I'm not skilled enough with PowerShell or programming to figure out why. I've tried added a Destination string, changing which folder is called what in the codes, but I'm not sure what's going on.

The intended result - and one I managed to get working once but apparently forgot to save - is that it will compare the Source folder (Test 1) with the Destination folder (2), and if a file is found to exist in Destination but not in Source, that file will be moved to Backup (Folder 3).

Does anyone have any clues?

Thanks

Windows for business | Windows Server | User experience | PowerShell
Windows for business | Windows Client for IT Pros | User experience | Other
0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.