1

I have a script right now that looks for all files certain day old and certain file extension and it deletes all of the files. This works fine and it counts fine

Then I have to delete all folders that correspond to being empty and that includes all sub folders too. I also have to output this into a file and display each file deleted. The output would show 30 folders deleted but actually 48 were really deleted.

Now my question is i am trying to do a count of all the folders deleted. I have this script but it just counts the deepest folders not all the ones deleted. Here is the part of the script i can not get to count

$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
Mr. L
  • 3,098
  • 4
  • 26
  • 26
Paul
  • 11
  • 2

2 Answers2

1

Although the sort call will correctly send each directory through the pipeline in nesting order, since they are not really being removed (remove-item -whatif), the parents will still contain their empty child directories and so will not pass the second condition (!(get-childitem $_.fullName -force)). Also note that Remove-Item does not produce any output, so the deleted directories will not appear in the log.

Adapting Keith Hill's answer to a similar question, here is a modified version of the original script that uses a filter to retrieve all empty directories first, then removes and logs each one:

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

Note that -Recurse was added to the call to Remove-Item, as empty child directories will remain when using -WhatIf. Neither flag should be needed when performing an actual remove on an empty directory.

Community
  • 1
  • 1
Emperor XLII
  • 13,014
  • 11
  • 65
  • 75
0

Not tested:

 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
mjolinor
  • 66,130
  • 7
  • 114
  • 135