Search code examples
windowspowershellstorage

Remove files with LastWriteTime


I have a folder containing subfolders with almost the same name i want to delete these subfolders with LastWriteTime in a descending order, but skip the first one. And keep the first one with the latest LastWriteTime.

Example "TestFolder-sep-XXXXXX"

If i add -Recurse on Remove-Item i get a bunch of errors "Cannot find path 'XXXXXXXXXXXXXX'" If i add -Recurse on get-childitem and remove-item i get no errors but the files are not deleted. If i only have -Recurse on get-childitem no files are deleted.

i have tried with $loc = "C:\Temp*" & $loc = "C:\Temp*"

$loc = "C:\temp"
$Sep = "TestFolder-sep*" 
Get-childitem -path $loc -name $Sep | sort LastWriteTime -Descending | Select -Skip 1 | Remove-Item -force

Solution

  • -Filter, not -Name is what you need in this instace.

    This will delete all sub-directories inside $loc which name starts with the value of $Sep:

    Get-ChildItem -Directory -Path $loc -Filter $Sep | Sort-Object -Property LastWriteTime -Descending | Select-Object -Skip 1 | Remove-Item -Recurse -Force -WhatIf

    As you need to only delete drectories I added -Directory to Get-ChildItem, thus automatically skipping files to minimize the risk of unintended deletions and to optimize the successive commands(especially useful in the case of many files)

    Then I did add -Recurse to Remove-Item so to skip the request for confirmation.

    -WhatIf is used to see what would get deleted without actually deleting anything.
    Remove it once you are sure the command works as intended.