Keep x number of directories and delete all the rest, you need to exclude one directory and its contents each time

I am trying to delete everything except the last 10 directories, always excluding the java directory. Unfortunately, it deletes all but the last 10 contents of the java directory.

I am trying to change the solution using the following link so that my situation works correctly: Store x number of files and delete all the 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 clear 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 } 
+4
source share
1 answer

OK, so this is a 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.

+3
source

Source: https://habr.com/ru/post/1411831/


All Articles