Powershell script - delete files older than, except one folder name

Lukasz Florek 0 Reputation points
2023-11-06T13:25:34.8333333+00:00

Hi, I've made a script that deletes files in folders and subfolders.

It works fine and looks like:

$limit = (Get-Date).AddDays(-0) $currentDate = Get-Date -Format "yyyyMMdd_HHmmss" $path = "C:\test" $LogFile = "C:\delete_log\delete_$currentDate.log"; # Delete files older than the $limit. Get-ChildItem -Path $path -Recurse -Force -Exclude 'Keep' | Where-Object { !$.PSIsContainer -and $.LastWriteTime -lt $limit } | Out-File -FilePath $LogFile -Append Get-ChildItem -Path $path -Recurse -Force -Exclude 'Keep' | Where-Object { !$.PSIsContainer -and $.LastWriteTime -lt $limit } | Remove-Item -Force

I would like to skip folder "_Keep" and what's in side - shouldn't be deleted.

I try to something like this but it's not working.

$limit = (Get-Date).AddDays(-0) $currentDate = Get-Date -Format "yyyyMMdd_HHmmss" $path = "C:\test" $exclude = "Keep" $logfile = "C:\delete_log\delete$currentDate.log"; # Excluding folders $files = get-childitem $path -Recurse | Where-object{$.fullname -notlike $exclude} # Delete files older than the $limit. Get-ChildItem -Path $files -Recurse -Force | Where-Object {!$.PSIsContainer -and $.LastWriteTime -lt $limit } | Out-File -FilePath $logfile -Append Get-ChildItem -Path $files -Recurse -Force | Where-Object {!$.PSIsContainer -and $_.LastWriteTime -lt $limit } | Remove-Item -Force

Any help? Please :)

Windows for business Windows Server User experience PowerShell
{count} votes

1 answer

Sort by: Most helpful
  1. MotoX80 36,291 Reputation points
    2023-11-06T15:51:13.84+00:00

    Try this.

    $limit = (Get-Date).AddDays(-8300) 
    $currentDate = Get-Date -Format "yyyyMMdd_HHmmss" 
    $path = "C:\temp\deleteme" 
    $exclude = "_Keep"                       #  Keep or _Keep?? 
    $logfile = "C:\temp\delete$currentDate.log"
    # Get folder names that don't contain _Keep 
    $folders = get-childitem $path -Recurse -Directory | Where-object{$_.fullname.split("\") -notcontains $exclude}    # account for subfolders under Keep 
    "Analyzing these folders." | Out-File -FilePath $logfile -Append
    ($folders).fullname | Out-File -FilePath $logfile -Append
    # Delete files older than the $limit.
    "Deleting these files." | Out-File -FilePath $logfile -Append 
    foreach ($f in $folders) {
        $files = Get-ChildItem -Path $f.FullName -File  -Force | Where-Object {$_.LastWriteTime -lt $limit }
        ($files).fullname | Out-File -FilePath $logfile -Append 
        $files | Remove-Item -Force -whatif 
    }
    # Get-Content $logfile      # for testing
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.