计算删除的空文件夹

时间:2011-03-04 13:24:39

标签: powershell

我现在有一个脚本,可以查找特定日期的所有文件和某些文件扩展名,并删除所有文件。这工作正常,它很好

然后我必须删除所有对应于空的文件夹,包括所有子文件夹。 我还必须将其输出到一个文件中并显示删除的每个文件。输出将显示删除30个文件夹,但实际上有48个文件夹已被删除。

现在我的问题是我正在尝试删除所有文件夹。我有这个脚本,但它只计算最深的文件夹而不是所有删除的文件夹。 这是我无法计算的脚本的一部分

$TargetFolder = "C:\Users\user\Desktop\temp"
$LogFile = "C:\Summary.txt"
$Count = 0

Date | Out-File -filepath $LogFile

get-childitem $TargetFolder -recurse -force | Where-Object {$_.psIsContainer}| sort fullName -des |
Where-Object {!(get-childitem $_.fullName -force)} | ForEach-Object{$Count++; $_.fullName} | remove-item -whatif | Out-File -filepath $LogFile -append

$Count = "Total Folders = " + $Count
$Count | Out-File -filepath $LogFile -append

2 个答案:

答案 0 :(得分:1)

虽然sort调用会以嵌套顺序正确地通过管道发送每个目录,因为它们实际上并没有被删除(remove-item -whatif),所以父节点仍然会包含它们的空子目录,所以不会传递第二个条件(!(get-childitem $_.fullName -force))。另请注意,Remove-Item不会产生任何输出,因此删除的目录不会出现在日志中。

Keith Hill's answer改编为similar question,这是原始脚本的修改版本,它使用过滤器首先检索所有空目录,然后删除并记录每个目录:

filter Where-Empty {
  $children = @($_ |
    Get-ChildItem -Recurse -Force |
    Where-Object { -not $_.PSIsContainer })
  if( $_.PSIsContainer -and $children.Length -eq 0 ) {
    $_
  }
}

$emptyDirectories = @(
  Get-ChildItem $TargetFolder -Recurse -Force |
  Where-Empty |
  Sort-Object -Property FullName -Descending)
$emptyDirectories | ForEach-Object {
  $_ | Remove-Item -WhatIf -Recurse
  $_.FullName | Out-File -FilePath $LogFile -Append
}

$Count = $emptyDirectories.Count
"Total Folders = $Count" | Out-File -FilePath $LogFile -Append

请注意-Recurse已添加到Remove-Item的调用中,因为使用-WhatIf时将保留空的子目录。在空目录上执行实际删除时,不需要任何标志。

答案 1 :(得分:0)

未经测试:

 get-childitem $TargetFolder -recurse -force |
 where-object{$_.psiscontainer -and -not (get-childitem $_.fullname -recurse -force | where-object {!($_.psiscontainer)}}|
 sort fullName -des |
 Where-Object {!(get-childitem $.fullName -force)} |
 ForEach-Object{$Count++; $_.fullName} |
 remove-item -whatif |
 Out-File -filepath $LogFile -append
相关问题