Home > Software design >  How to delete all but the most recent files in a directory of folders and files
How to delete all but the most recent files in a directory of folders and files

Time:03-31

I have a folder that has a bunch of backups in in separated by folder. I want a script to use the directory (C:\Users\user\Desktop\TEST) and in that directory I have any number of folders with any number of files in them, I only want to keep the latest in the folder for every folder in the directory and delete the rest.

I have this but it only does 1 folder at a time and it has to be hardcoded.

$path = "C:\Users\user\Desktop\TEST\Folder1"
$FileNumber = (get-childitem $path).count - 1
get-childitem -path $path | sort CreationTime -Descending | select -last $FileNumber |  Remove-Item -Force -WhatIf

Is there any way to automate this?

Thanks,

CodePudding user response:

You can try this:

$Path = "C:\Users\user\Desktop\TEST"
$Folders = Get-ChildItem $Path
foreach ($Folder in $Folders)
{
    $FolderName = $Folder.FullName
    $Files = Get-ChildItem -Path $FolderName
    $FileNumber = $Files.Count - 1
    $Files | sort CreationTime -Descending | select -last $FileNumber | Remove-Item -Force -WhatIf
}

CodePudding user response:

You would need a loop of your choice to accomplish this, this example uses ForEach-Object. Instead of using Select-Object -Last N you could just use Select-Object -Skip 1 to skip the newest file. Also note the use of -Directory and -File with Get-ChildItem to filter only directories or only files.

$path = "C:\Users\user\Desktop\TEST\Folder1"

# Get all Directories in `$path`
Get-ChildItem $path -Directory | ForEach-Object {
    # For each Directory, get the Files
    Get-ChildItem $_.FullName -File |
        # Sort them from Newest to Oldest
        Sort-Object CreationTime -Descending |
        # Skip the first 1 (the newest)
        Select-Object -Skip 1 |
        # Remove the rest
        Remove-Item -Force -WhatIf
}
  • Related