This script uses robocopy purge with list command to out what would be purged it then parses that log file and checks each file and only deletes files older than 7 days. Is there way it could be simplified to maybe use less log files in the process?
$Log = "D:\IT\Backups\Logs\list.txt"
$extrafile = "D:\IT\Backups\Logs\extrafile.txt"
$extradir = "D:\IT\Backups\Logs\extradir.txt"
$extraparsed = "D:\IT\Backups\Logs\extraparsed.txt"
$purged = "D:\IT\Backups\Logs\purged.txt"
$now = Get-Date
$days = "7"
$Lastwrite = $now.AddDays(-$days)
$datetime = get-date -f MM-dd-yy-hhmmtt
If (Test-Path "D:\IT\Backups\Logs\list.txt"){
Remove-Item "D:\IT\Backups\Logs\list.txt"
}
robocopy "\\10.10.10.9\tcart" "\\192.168.1.44\tcartbkup" /e /Purge /R:1 /W:1 /l /TEE /FP /LOG:"D:\IT\Backups\Logs\list.txt" /MT:16
If (Test-Path $extradir){
Remove-Item $extradir
}
If (Test-Path $extrafile){
Remove-Item $extrafile
}
If (Test-Path $extraparsed){
Remove-Item $extraparsed
}
If (Test-Path $purged){
rename-item $purged -newname ("purged-" + $datetime + ".txt")
}
Get-Content $Log | Select-String "EXTRA File" | Out-File $extrafile -Width 5000
Get-Content $Log | Select-String "EXTRA Dir" | Out-File $extradir -Width 5000
cat $extradir | %{$_.Substring(28)} | Out-File $extraparsed
cat $extrafile | %{$_.Substring(38)} | Out-File $extraparsed -Append
$files = Get-Content $extraparsed | Select-String "\\" | ForEach-Object {(Get-Item "$_")} | Where {ForEach-Object {($_.LastWriteTime -le "$Lastwrite")}}
foreach ($file in $files)
{
if ($File -ne $NULL)
{
Write-Host "Deleting File $File" -ForegroundColor "DarkRed"
Write-Output "Deleting File $File" | Out-File $purged -Append
Remove-Item $file.FullName -Recurse | Out-Null
}
else
{
Write-Host "No More files to delete" -ForegroundColor "Green"
Write-Output "No More files to delete" | Out-File $purged -Append
}
}