Keep X folders in a directory

156 Views Asked by At

I'm working on keeping a archive directory of folders. Each folder contains multiple files representing a backup of an application instance for the day and the folder is created (and named) based on the day the backup was created. I want to keep X folders available at a given time and delete the older folders.

I attempted to implement a solution based on this previously answered question.

My new code is as follows:

gci E:\sql_backups\Everything\Archive -Recurse|where {-not $_PsIsContainer}|sort CreationTime -desc| select -Skip X| Remove-Item -Force

There are two issues I'm running into. The first is that when the script is run it will still prompt for the recursion UI prompt for recursion.

The second issue is that it is now removing all folders from the directory, regardless of the value of X.

2

There are 2 best solutions below

3
Doug Maurer On

Since you are strictly returning files, you will have to do a little more work. As I commented, you are missing a period in $_.PsIsContainer. This should achieve your desired result.

Get-ChildItem E:\sql_backups\Everything\Archive -Recurse |
    Where-Object {-not $_.PsIsContainer}| Sort-Object CreationTime -desc |
        Select-Object -Skip X | Foreach-Object {Remove-Item $_.PSParentPath -Recurse -Force}

Also, in powershell version 3.0 and up there exist -File and -Directory parameters so you can replace your where clause with -File

Get-ChildItem E:\sql_backups\Everything\Archive -Recurse -File |
    Sort-Object CreationTime -desc | Select-Object -Skip X |
        Foreach-Object {Remove-Item $_.PSParentPath -Recurse -Force}
0
JLieske On

I ended up using this to solve the problem.

gci E:\sql_backups\Everything\Archive -Recurse|where {$_.PsIsContainer}|sort CreationTime -desc| select -Skip X| Remove-Item -recurs-force

Looking at it, it will likely have issues with folders created at the same time (arbitrarily choosing which to remove), but given I'm doing daily folder creation this seems acceptable for my needs.