PowerShell Script to Copy Most Recent Files

I am trying to write a PowerShell script that will select the most recent SQL backup file for each of my databases and then copy that file to another directory and then run WinRAR on those files to "zip" them up so that our online backup program (MozyPro) can back up this one compressed file.  The files are all stored in C:\MSSQL\Data\Backup with each database having it's own folder.  Also each folder holds 2 weeks of backup files, so I want the script to just select the most recent file from each folder.  The following Power Shell script works fine to list the files:

PS C:\MSSQL\Data\Backup> ls -r -fi *.bak | sort @{expression={$_.LastWriteTime};Descending=$true} | select Directory,
Name, LastWriteTime | Group-Object Directory | %{$_.Group | Select -first 1}

And this command will invoke WinRAR to "zip" up files that have been copied to C:\Mozy:
rar a -r "C:\Mozy\SQLBackups.rar" "C:\Mozy\*.bak"

Now how do I combine the two?  Basically how to I tell PowerShell to copy the files and then invoke WinRAR?
Who is Participating?
This should do it.

$source = "C:\MSSQL\Data\Backup"
$filter = "*.bak"
$dest = "C:\Mozy"
$command = 'rar'
$switches = 'a -r "' + $dest + '\SQLBackups.rar" "' + $dest + '\' + $filter + '"'
ls -path $source -fi $filter | sort-object LastWriteTime | select-object -last 1 | copy-item -dest $dest
[Diagnostics.Process]::Start($command, $switches)

Open in new window

bmcclearyAuthor Commented:
Thank you very much.  That was very helpful.  I needed to tweak it a bit because without the "-r" switch it wouldn't recurse through the subdirectories, and even after I added the "-r" switch, it would only select the one most recently modified file in all of the directories combined, not the most recently modified file in each sub directory.  Therefore, my final command looks like the following:

ls -r -path "C:\MSSQL\Data\Backup" -fi *.bak | sort @{expression={$_.LastWriteTime};Descending=
$true} | select-object | Group-Object Directory | %{$_.Group | Select -first 1} | copy-item -dest "C:\Mozy"

So now I have two questions for you...
1) Do you see any issues with the modified line I posted and if it would miss any files (e.g. inconsistant sort, etc.)?
2) Is there anyway that I can combine the line I just wrote with the "[Diagnostics.Process]::Start($command, $switches)" line so I can run it as one command from within Task Scheduler, or will I have to save the two lines to a .ps1 file and run that?

Again, I appreciate all the help!
bmcclearyAuthor Commented:
One last question (we'll call it #3)...
After WinRAR zips up the files, the *.bak file are left in that folder.  Is there anyway I can delete those files when WinRAR completes it's process?
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.