计数已删除的空文件夹

问题描述:

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

然后,我必须删除所有相应的文件夹是空的,也包括所有的子文件夹。 我也必须输出到一个文件并显示每个文件删除。输出将显示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 

未测试:

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 
+0

这似乎做同样的事情相同的输出发生 – Paul 2011-03-04 15:28:07

虽然排序通话将正常通过嵌套顺序管道发送的每个目录,因为它们是没有被真正删除(remove-item -whatif),父母仍将包含空的子目录,因此不会通过第二个条件(!(get-childitem $_.fullName -force))。另请注意,Remove-Item不会产生任何输出,因此删除的目录不会出现在日志中。

适应Keith Hill's answersimilar 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加入当使用-WhatIf时,作为空子目录的电话Remove-Item将保持不变。在空目录上执行实际删除时,不应该需要标志。