PowerShell script to get only the most recent backups

Here’s a neat PowerShell script to grab only the most recent backup files.  Given a path, it will recurse the directories and only return the most recent *.bak file in all subdirectories.

$path = "H:\SourceDir"
$destPath = "\\Destination"

function CopyLastBackup
{
    try
    {
        Remove-Item "$destPath\*" -include "*.bak"
        $dirs = Get-ChildItem $path | where {$_.PSIsContainer} | where {$_.GetFiles().Count -ne 0}
        foreach($dir in $dirs)
        {
			$file = Get-ChildItem -LiteralPath $dir.FullName -include "*.bak" | sort CreationTime -Descending | select -First 1
        	Copy-Item -LiteralPath $file.FullName -Destination $destPath -force
            write-host $file 
        }
        return 0;
    }
    catch
    {
        write-host $error[0]
        return 1
    }
    
}


$ret = CopyLastBackup
if($ret -eq 1)
{
    throw "Failure"
}