Search code examples
windowspowershellcmdansible

powershell Deleting all folders except the last three


I have a folder D:/Tests on a Windows machine, it stores folders that are created every day. I need code that runs with ansible on a linux machine that will delete all folders except the last three created ones. I've dug through dozens of articles in stackoverflow, but most of these issues are solved using bat files. For me, this option is not suitable. From what I found, here is the most similar to what I need:

Get-Childitem D:\Downloads_D -recurse | where {($_.creationtime -gt $del_date) -and ($_.name -notlike "*dump*" -and $_.name -notlike "*perform*")} | remove-item 

But my knowledge of Powershell is not enough to edit it so that it performs my task. Is there any way to achieve my goal using ansible modules, a Windows command line command, or a Powershell command?


Solution

  • For powershell, you could do the following:

    Get-ChildItem -Path D:\Downloads_D -Directory | Sort-Object -Property CreationTime | Select-Object -SkipLast 3 | Remove-Item
    

    Explanation

    • Filter directories using -Directory from Get-ChildItem
    • Sort directories by CreationTime property using Sort-Object
    • Skip last 3 directories using Select-Object and -SkipLast 3. This ensures the 3 most recently created directories are not removed.
    • Pipe to Remove-Item to remove the directories