0

I simply want to delete empty folders in a path along with folders that only have .txt files. I have this, but it doesn't work.

$tdc = "C:\My Shared Folder"

while (
    $empties = Get-ChildItem $tdc -Recurse -Directory | Where {
        (GCI -Path $_.FullName -File -Exclude ("*.txt") | Measure-Object).Count -eq 0 -and
        $_.GetDirectories().Count -eq 0
    }
) {
    $empties | Remove-Item -Force -Verbose
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
user1612851
  • 1,144
  • 4
  • 18
  • 32
  • read in the list of dirs, sort by length of the full name [longest 1st], check for _only txt_ files, del those dirs, check for _no_ files, dell those dirs. ///// the sort lets you kill dirs from the bottom to the top of any given dir tree. – Lee_Dailey Jun 27 '19 at 17:00
  • 2
    Try one of the answers here:[How to recursively remove all empty folders in PowerShell?](https://stackoverflow.com/questions/28631419/how-to-recursively-remove-all-empty-folders-in-powershell) or here: [Powershell to delete all files with a certain file extension](https://superuser.com/questions/1091344/powershell-to-delete-all-files-with-a-certain-file-extension) – techguy1029 Jun 27 '19 at 19:13
  • `Get-ChildItem $tdc -Recurse -Directory | Where-Object {-not (Get-ChildItem $_.FullName -Exclude '*.txt')} | Remove-Item -Force -Verbose`? – Ansgar Wiechers Jun 28 '19 at 09:25
  • @AnsgarWiechers That is closer, but deletes folders that have a subfolder with files in it. I tried modifying it for that, but it still is deleting those. Get-ChildItem $tdc -Recurse -Directory | Where-Object {(-not (Get-ChildItem $_.FullName -Exclude '*.txt')) -and $_.GetDirectories().Count -eq 0 } | Remove-Item -Force -Verbose -WhatIf -Recurse – user1612851 Jun 28 '19 at 12:52

0 Answers0