2

I'm trying to create a powershellscript to schedule backup delete so that the HDD doesn't get full.

  • What I want to do is to verify which file that is the newest
  • Afterwards I want to check if the filesize doesn't different more than 10% from the second newest file.
  • If the filesize is within the size range then delete all but the newest ones.
  • If the filesize is smaller or bigger than 10% of the second newest file then delete all but the newest and the second newest file.

I would like you guys to help me out how I should think to formulate the code to make this to work.

I've started with below which deletes all files older than 2 days but I'm not quite sure how to change that to keep the newest file not depending of days.

$Path = "C:\Temp\Backup\Folder1\"
$Days = 2
$Date = Get-Date
$Include = "*.gpg"
$Exclude = "*.txt"

Get-ChildItem $Path -Recurse |
Where-Object {-not $_.PSIsContainer -and $Date.Subtract($_.CreationTime).Days -gt $Days } |
Remove-Item -WhatIf

1 Answers1

2

You could do something like this:

$BackupFiles = Get-ChildItem -File | Sort-Object LastWriteTime -Descending

$LatestBackup = $BackupFiles | Select -First 1
$PrevBackup = $BackupFiles | Select -Skip 1 -First 1

$BackupSizeThreshold = $PrevBackup.Length * 0.1


$FilesToRemove = If ($LatestBackup.Length -le ($PrevBackup.Length + $BackupSizeThreshold) -and $LatestBackup.Length -ge ($PrevBackup.Length - $BackupSizeThreshold)) {
    $BackupFiles | Select -Skip 1
}
Else {
    $BackupFiles | Select -Skip 2
}

$FilesToRemove | Remove-Item -WhatIf

Remove the -WhatIf if you're seeing the results you expect.

Mark Wragg
  • 22,105
  • 7
  • 39
  • 68
  • Thanks a lot. Just a question. I tried to add -Exclude *.txt at Get-ChildItem but the code stop working when I do that. I would like to exclude some files from de folder. – Markus Sacramento Mar 08 '19 at 09:04
  • 1
    That's strange, `-Exclude` doesn't seem to work when used with `-File`. You have two options, either exclude your files via a `| Where-Object {$_.name -notlike '*.txt'}` or use `-Exclude` on Get-ChildItem and if you need to also exclude folders use a `| Where-Object {-not $_.PSIsContainer}`. If your backup folder doesn't have subfolders in it you don't need to worry about it obviously and you can just do away with using `-File` and use `-Exclude`. – Mark Wragg Mar 08 '19 at 11:10
  • Or this offers another solution: https://stackoverflow.com/questions/43191453/get-childitem-exclude-and-file-parameters-dont-work-together – Mark Wragg Mar 08 '19 at 11:12