none
Empty folders with exclusion directories RRS feed

  • Question

  • I'm really new to Powershell and I'm trying to clean up empty folders in users home folders. It will run and delete empty folders but won't exclude the directory and the sub directories within it. Any suggestions?  

    $rootPath = "C:\test"
    # Get each item under the current directory recursively
    foreach($childItem in (Get-ChildItem $rootPath -Recurse))
    {
    # if it's a folder AND does not have child items of its own
    if( ($childItem.PSIsContainer) -and (!(Get-ChildItem -Recurse -Path $childItem.FullName)))
    {
    # Delete it
    Remove-Item $childItem.FullName -Confirm:$false
    }
    }
    • Edited by Mavareno Friday, March 9, 2018 1:22 PM
    • Moved by Bill_Stewart Tuesday, May 8, 2018 6:27 PM Abandoned
    Friday, March 9, 2018 1:12 PM

All replies

  • You have to remove empty folder from the leaf back to the root where there are no files and no included folders.  

    $emptyFolders = Get-ChildItem $path -Directory -Recurse | Where{ $_.GetFiles().Count -eq 0 -and $_.GetDirectories().Count -eq 0}

    Remove these and run in loop until no folders are found.


    \_(ツ)_/

    Friday, March 9, 2018 5:11 PM