Blogs

Blogs

Powershell - Copy Files and Folders and Delete Files Older Than X Days

Recently I needed to copy all files and folders in one location to another and then delete files older than X days in the destination folder and I would need to do this quite regularly. Being a programmer I decided that rather than doing this manually it would make sense to write a quick Powershell script that would do it for me and that could be reused.

$maxAge = (Get-Date).AddDays(-3)
$startPath = "C:\something\start\"
$destinationPath = "D:\something\destination\"

if (Test-Path $startPath)
{
    if (Test-Path $destinationPath)
    {    
        Get-ChildItem -Path $destinationPath -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $maxAge } | Remove-Item -Force
        Get-ChildItem -Path $destinationPath -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse

        $startPath = $startPath + "*"
        Copy-Item $startPath $destinationPath -Force -Recurse
    }
}

As you can see you declare the max age for your files in the destination folder, the start path (this is where you are going to copy files from) and then the destination folder. I then test that these folders exist, if they do then I delete all the files and folders in the destination path along with any empty folders that are left behind. I then update my start path so that it will now include all of it’s children, I do this by using the * wildcard, I  then copy all of the files and folder across. I use force (this will overwrite any that were already there) and recurse (this will then rerun this function for all of the subfolders).

I hope that you find this useful and that it saves you time!

This website uses cookies to provide the best possible experience. By continuing to use our website you are agreeing to our use of cookies.