[英]Remove certain folders recursively?
我有一个看起来像这样的文件夹结构
-2018
--01-Jan
--02-Feb
--etc
-2017
--01-Jan
--02-Feb
--etc
有没有办法删除所有超过 7 年的目录(根据这个命名结构......而不是根据创建/修改日期等)?
所以如果我在 2018 年 8 月运行它,我会留下
-2018
-2017
-2016
-2015
-2014
-2013
-2012
-2011
--08-Aug
--09-Sep
--10-Oct
--11-Nov
--12-Dec
因此 2012 - 2018 文件夹将保持不变。 任何文件夹 2010 及更早版本都将被删除。 并且 2011 '07-Jul' 或更小的任何文件夹都将被删除。
谢谢P
我首先使用以下代码创建了一个类似的文件夹结构:
##
## define enum for months
##
enum month {
Jan = 1
Feb = 2
Mar = 3
Apr = 4
May = 5
Jun = 6
Jul = 7
Aug = 8
Sep = 9
Oct = 10
Nov = 11
Dec = 12
}
##
## create folder structure
##
New-Item -Path c:\ -Name Testdata -ItemType Directory
2018..2005 |
foreach {
New-Item -Path c:\Testdata -Name $psitem -ItemType Directory
$path = "c:\Testdata\$psitem"
1..12 |
foreach {
$name = "{0:00}-{1}" -f $psitem, [month]$psitem
New-Item -Path $path -Name $name -ItemType Directory
}
}
这给了我一个简单的结构来测试。 我假设您的年份文件夹是某些东西的子文件夹。 如果它们位于也能正常工作的驱动器的根目录中。
要删除文件夹:
enum month {
Jan = 1
Feb = 2
Mar = 3
Apr = 4
May = 5
Jun = 6
Jul = 7
Aug = 8
Sep = 9
Oct = 10
Nov = 11
Dec = 12
}
$date = Get-Date
$year = $date.Year - 8
##
## delete evreything 8 years or older
##
Get-ChildItem -Path C:\Testdata -Directory |
where Name -le $year |
foreach {
Remove-Item -Path $psitem.Fullname -Recurse -Force -Confirm:$false
}
##
## if Month -ne January
## need to delete some months
##
if ($date.Month -gt 1){
$path = "C:\testdata\$($year+1)"
$month = $date.Month -1
1..$month |
foreach {
$mpath = "$path\{0:00}-{1}" -f $psitem, [month]$psitem
Remove-Item -Path $mpath -Recurse -Force -Confirm:$false
}
}
我对您使用的三个字母缩写进行了假设,但您可以轻松更改枚举。
该代码获取当前日期并获取年份减去 8。它循环遍历您的顶级文件夹并获取小于或等于您定义的年份的文件夹。 它们及其内容将被强制删除。 唯一可以停止删除的是,如果您打开了其中一个文件。
如果当前月份是 1 月,则无事可做。 否则,创建 -7 年文件夹的路径并计算您要删除的最后一个月。 遍历月份,构建路径并强制删除文件夹及其内容。
大部分工作是在年度级别完成的,并快速清理了几个月。 我建议测试几个月来检查你需要的逻辑。
好的,这非常简单,它需要您进行一些编码并本质上使用嵌套循环。 您需要了解的是如何使用 Get-Date 动词。 因此,将在 2011 年之前递归删除所有数据的示例如下所示
# Set your Path
$MyFolderPath = "C:\MyPath"
# Define the object to hold the folders (We are only looking for Folders not files)
$folders = Get-Childitem -Path $MyFolderPath -Directory
# Loop through each folder
foreach($folder in $folders)
{
# Using a cast to integer compare the Year using the folder name with the
# Get-Date function -7 years from this year
if([int]$folder.Name -lt (Get-Date).AddYears(-7).Year)
{
# Now remove the entire folder recursively without prompting.
Remove-Item $folder.FullName -Recurse -Force -Confirm:$false
}
}
现在达到了月的水平。 我会让你玩一个嵌套循环并达到那个级别。 我希望这可以帮助你...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.