保留x个目录并删除所有其他目录,每次都需要排除一个目录及其内容

时间:2012-05-10 17:32:03

标签: powershell

我试图删除除10个最新目录之外的所有目录,总是排除java目录。不幸的是,除了最后10个“java”目录的内容之外,它正在删除。

我一直在尝试从以下链接修改解决方案,以使我的情况正常运行: Keep x number of files and delete all others - PART TWO

目录结构如下:

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

我的计划是运行第二个脚本来清理java子目录。

#----- 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
}

1 个答案:

答案 0 :(得分:3)

好的,所以这是我提出的脚本,抱歉,这是我的第一个PowerShell脚本......

$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
}

这些回声可以帮助我调试,随时删除它们。