Payette1996
Payette1996

Reputation: 1

Powershell delete files older than 30 days but exclude certain folders and their contents

Here is my current code but sadly it deletes excluded folder contents. I want to keep folder contents that are inside an excluded folder.

I've been trying for days but can't find a solution. Maybe this is a PowerShell limitation?

$path = "C:\Users\bob\Desktop\testfolder"
$exclude = @('FOLDERNAME', 'filename.txt')
$lastWrite = (Get-Date).AddDays(-30)

Get-ChildItem -Path $path -Recurse -Exclude $exclude | Where-Object {$_.LastWriteTime -le $lastWrite} | Remove-Item

Method 2 (doesn't function) :

$results = Get-ChildItem -Path $path -Recurse | Where-Object {$_.LastWriteTime -le $lastWrite}
$path = "C:\Users\louisp\Desktop\testfolder"
$exclude = @('oldkeep', 'oldkeep2', 'important')
$lastWrite = (Get-Date).AddDays(-30)

foreach ($item in $results) {
   $noExeption = $true
   foreach($exeption in $exclude){
      if($item.name -eq $exeption){
         $noExeption = $false
         break
      }
   }
   if($noExeption) {
      remove-item $item
   }
}

Upvotes: 0

Views: 2043

Answers (2)

KarKzas
KarKzas

Reputation: 11

There is the code I use. maybe a little rustic, but it works.

$age = (Get-Date).AddDays(-30)

Get-ChildItem C:\Folder -Exclude Z*, FolderName | foreach{
    if ($_.LastWriteTime -le $age){
        Remove-Item $_.fullname -Recurse -Force -Confirm:$false
    }
}

Upvotes: 1

Dom
Dom

Reputation: 418

I suggest to following workaround art two:

$results= Get-ChildItem -Path $path -Recurse | Where-Object {$_.LastWriteTime -le $lastWrite} 
foreach ($item in $results){
   $notExeption=$true
   foreach($exeption in $exclude){
      if($item.name -eq $exeption){
         $noExeption=$false
         break
      }
   }
   if($noexeption){
      remove-item -LiteralPath $item.name
   }
}

Upvotes: 0

Related Questions