Script is removing folders that still have content!

I have a script that is designed to remove files after nine days and then removes folders that are empty unless it is named _TrendforMac. The problem is that the script removes folders that have folders still under it. If you create a folder tree several levels deep with the lowest level child folder called “_trendformac”, it will remove the parent folder even though it still has “content”.
Thank you for any help!

Delete the empty folders after cleanup of files unless the folder is named _TrendForMac

Get-ChildItem -Path $path -Recurse -Force | Where-Object { $.PSIsContainer -and $.Name -ne "TrendForMac" -and (Get-ChildItem -Path $.FullName -Recurse -Force ) -eq $null } | Remove-Item -Recurse -Force

Can you post an example tree? I’m not able to reproduce your findings.

To be able to debug this more, I’d start by seperating the folder collection from the folder removal, for example:

$EmptyFolders = Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and $_.Name -ne "_TrendForMac" -and (Get-ChildItem -Path $_.FullName -Recurse -Force ) -eq $null }

If($EmptyFolders)
{
   Write-Host $EmptyFolders
   $EmptyFolders | Remove-Item -Recurse -Force
}

You can decide for yourself if you’d like to display the empty folders to the console, or add them to a logfile, just what you like. This might help you to understand what’s happening.

So you might try this below and add a pipe in between your where-object statement and the remove-item statement for “Where-Object {!$_.PSIsContainer}) -eq $null”

Get-ChildItem -Path $path -Recurse -Force | Where-Object { $.PSIsContainer -and $.Name -ne "TrendForMac" -and (Get-ChildItem -Path $.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse

You can also use your existing or what I posted above to run it with a whatif switch:

Get-ChildItem -Path $path -Recurse -Force | Where-Object { $.PSIsContainer -and $.Name -ne "TrendForMac" -and (Get-ChildItem -Path $.FullName -Recurse -Force ) -eq $null } | Remove-Item -Recurse -Whatif

Get-ChildItem -Path $path -Recurse -Force | Where-Object { $.PSIsContainer -and $.Name -ne "TrendForMac" -and (Get-ChildItem -Path $.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Recurse -Whatif

Hope this helps!

After your comment about not being able to recreate the issue, i went back and tried the operation on a Windows 8 laptop with no issues. I then went back and tried the operation again from my Windows 2008 R2 server that i had experienced the problem on originally, and it worked correctly there as well! It has been a good while since i tested the functionality of the part that was broken, so it must have been an update that corrected the problem. I apologize for posting when the problem was already corrected.
Thank you for the prompt response!