如何使用PowerShell删除空的子文件夹? [英] How to delete empty subfolders with PowerShell?

查看:538
本文介绍了如何使用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:\Junk\subfolder1a\subfolder2a\FILE3a

C:\Junk\subfolder1a\subfolder2a\subfolder3a

C:\Junk\subfolder1a\subfolder2B\FILE3b

所需结果:

  • 删除:FILE3bsubfolder2B& subfolder3a.
  • 离开:subfolder1asubfolder2aFILE3a.
  • Delete: FILE3b, subfolder2B & subfolder3a.
  • Leave: subfolder1a, subfolder2a, and FILE3a.

我可以递归清理文件.如何清理子文件夹而不删除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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆