如何使用 PowerShell 删除空子文件夹? [英] How to delete empty subfolders with PowerShell?
问题描述
我有一个共享,它是面向最终用户的垃圾抽屉".他们能够创建他们认为合适的文件夹和子文件夹.我需要实现一个脚本来删除创建超过 31 天的文件.
I have a share that is a "junk drawer" for end-users. They are able to create folders and subfolders as they see fit. I need to implement a script to delete files created more than 31 days old.
我从 Powershell 开始.我需要通过删除现在为空的子文件夹来跟进文件删除脚本.由于子文件夹的嵌套,我需要避免删除一个没有文件的子文件夹,但它下面有一个包含文件的子文件夹.
I have that started with Powershell. I need to follow up the file deletion script by deleting subfolders that are now empty. Because of the nesting of subfolders, I need to avoid deleting a subfolder that is empty of files, but has a subfolder below it that contains a file.
例如:
FILE3a
已有 10 天了.FILE3
已有 45 天了.- 我想清理结构,删除超过 30 天的文件,并删除空子文件夹.
FILE3a
is 10 days old.FILE3
is 45 days old.- I want to clean up the structure removing files older than 30 days, and delete empty subfolders.
C:Junksubfolder1asubfolder2aFILE3a
C:Junksubfolder1asubfolder2asubfolder3a
C:Junksubfolder1asubfolder2BFILE3b
想要的结果:
- 删除:
FILE3b
、subfolder2B
&subfolder3a
. - 离开:
subfolder1a
、subfolder2a
和FILE3a
.
- Delete:
FILE3b
,subfolder2B
&subfolder3a
. - Leave:
subfolder1a
,subfolder2a
, andFILE3a
.
我可以递归地清理文件.如何在不删除 subfolder1a
的情况下清理子文件夹?(垃圾"文件夹将始终保留.)
I can recursively clean up the files. How do I clean up the subfolders without deleting subfolder1a
? (The "Junk" folder will always remain.)
推荐答案
我会分两遍执行此操作 - 先删除旧文件,然后删除空目录:
I would do this in two passes - deleting the old files first and then the empty dirs:
Get-ChildItem -recurse | Where {!$_.PSIsContainer -and `
$_.LastWriteTime -lt (get-date).AddDays(-31)} | Remove-Item -whatif
Get-ChildItem -recurse | Where {$_.PSIsContainer -and `
@(Get-ChildItem -Lit $_.Fullname -r | Where {!$_.PSIsContainer}).Length -eq 0} |
Remove-Item -recurse -whatif
这种类型的操作演示了 PowerShell 中嵌套管道的强大功能,第二组命令演示了这一点.它使用嵌套管道递归确定任何目录下是否有零个文件.
This type of operation demos the power of nested pipelines in PowerShell which the second set of commands demonstrates. It uses a nested pipeline to recursively determine if any directory has zero files under it.
这篇关于如何使用 PowerShell 删除空子文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!