Reputation:
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?
Upvotes: 2
Views: 2218
Reputation: 26335
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
-Directory
from Get-ChildItem
CreationTime
property using Sort-Object
Select-Object
and -SkipLast 3
. This ensures the 3 most recently created directories are not removed.Remove-Item
to remove the directoriesUpvotes: 7