I am trying to delete all but the 10 most recent directories, always excluding the java directory. Unfortunately it is deleting all but the last 10 the contents of the "java" directory too.
I've been trying to modify the solution from the following link to get my situation to work properly: Keep x number of files and delete all others - PART TWO
The directory structure is as follows:
dev_app_backup\java
dev_app_backup\2012-05-09_01-00-05_commnXsl (contains Xsl files)
dev_app_backup\2012-05-09_01-00-05_published (contains zip files)
dev_app_backup\various-dates-time_commonXsl
dev_app_backup\various-dates-time_published
My plan is to run a second script to clean out the java subdirectories.
#----- define folder where files are located ----#
$TargetFolder = "\\test\TestShare\dev_app_backup\*"
#----- number of directories to keep ----#
$keep = 10
#----- get zip files based on lastwrite filter ---#
$files = Get-Childitem $TargetFolder -recurse -exclude java
if ($files.Count -gt $keep)
{
$files | Sort-Object -property $_.LastWriteTime | Select-Object -First ($files.Count - $keep) | Remove-Item -Force
}
Using Extended Globbing and Pattern Matching Operators Also, with the ! operator, we can exclude all files we don't want glob to match during deletion. Let's look at the list of pattern matching operators: ?(pattern-list) matches at least zero and at most one occurrence.
Click the first file or folder you want to select. Hold down the Shift key, select the last file or folder, and then let go of the Shift key. Hold down the Ctrl key and click any other file(s) or folder(s) you would like to add to those already selected.
To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.
OK, so this is the script I came up with, sorry, this is my first powershell script...
$TargetFolder = "\test\TestShare\dev_app_backup*"
$keep = 10
$folders = Get-Childitem $TargetFolder -exclude java*
echo "folders"
echo $folders
echo "endfolders"
echo $folders.Count
echo $folders | Sort-Object -property $_.LastWriteTime | Select-Object -First ($folders.Count - $keep)
foreach ($folder in $folders | Sort-Object -property $_.LastWriteTime | Select-Object -First ($folders.Count - $keep))
{
echo $folder
$files = Get-Childitem $folder -recurse
echo $files
Remove-Item -Force $folder\$files
Remove-Item -Force $folder
}
The echoes are just there to help me debug, feel free to remove them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With