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
-Filter, not-Nameis what you need in this instace.This will delete all sub-directories inside
$locwhich 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 -WhatIfAs you need to only delete drectories I added
-DirectorytoGet-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
-RecursetoRemove-Itemso to skip the request for confirmation.-WhatIfis used to see what would get deleted without actually deleting anything.Remove it once you are sure the command works as intended.