如何递归删除PowerShell中的所有空文件夹? [英] How to recursively remove all empty folders in PowerShell?

查看:50
本文介绍了如何递归删除PowerShell中的所有空文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 PowerShell 中递归删除特定文件夹的所有空文件夹(检查任何级别的文件夹和子文件夹).

I need to recursively remove all empty folders for a specific folder in PowerShell (checking folder and sub-folder at any level).

目前我使用这个脚本没有成功.

At the moment I am using this script with no success.

你能告诉我如何解决吗?

Could you please tell me how to fix it?

$tdc='C:\a\c\d\'
$a = Get-ChildItem $tdc -recurse | Where-Object {$_.PSIsContainer -eq $True}
$a | Where-Object {$_.GetFiles().Count -eq 0} | Select-Object FullName

我在 Windows 8.1 版本上使用 PowerShell.

I am using PowerShell on Windows 8.1 version.

推荐答案

你可以使用这个:

$tdc="C:\a\c\d"
$dirs = gci $tdc -directory -recurse | Where { (gci $_.fullName).count -eq 0 } | select -expandproperty FullName
$dirs | Foreach-Object { Remove-Item $_ }

$dirs 将是过滤后从 Get-ChildItem 命令返回的空目录数组.然后,您可以遍历它以删除项目.

$dirs will be an array of empty directories returned from the Get-ChildItem command after filtering. You can then loop over it to remove the items.

如果您想删除包含空目录的目录,您只需要继续运行脚本,直到它们全部消失.您可以循环直到 $dirs 为空:

If you want to remove directories that contain empty directories, you just need to keep running the script until they're all gone. You can loop until $dirs is empty:

$tdc="C:\a\c\d"
do {
  $dirs = gci $tdc -directory -recurse | Where { (gci $_.fullName).count -eq 0 } | select -expandproperty FullName
  $dirs | Foreach-Object { Remove-Item $_ }
} while ($dirs.count -gt 0)

如果您想确保隐藏的文件和文件夹也将被删除,请包含 -Force 标志:

If you want to ensure that hidden files and folders will also be removed, include the -Force flag:

do {
  $dirs = gci $tdc -directory -recurse | Where { (gci $_.fullName -Force).count -eq 0 } | select -expandproperty FullName
  $dirs | Foreach-Object { Remove-Item $_ }
} while ($dirs.count -gt 0)

这篇关于如何递归删除PowerShell中的所有空文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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