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"
}
 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.