Find folders with only one file

Solution 1:

Simple enough with PowerShell:

cd C:\Parent
Get-ChildItem | Where-Object { $_.IsPSContainer -and @(Get-ChildItem $_).Count -eq 1 } | Remove-Item -Recurse

Explanation:

  • The second line consists of multiple commands, each of which has its output sent to the next one using the | (pipe) character.

  • Get-ChildItem returns a list of all files and folders in the current folder.

  • Where-Object allows us to filter that list, to get only the folders that match the criteria. $_ refers to the current object for each iteration.

    • $_.IsPSContainer returns true only for folders, so this allows us to exclude any files in the parent directory.

    • @(Get-ChildItem $_).Count -eq 1 is true only for folders that have exactly 1 file or subfolder inside them. The @ sign is necessary for the Count property to work correctly when there's only 1 item (see here for the explanation).

  • Finally, Remove-Item deletes each folder that made it through the filter. The -Recurse parameter is needed to automatically delete non-empty folders; without it, PowerShell would prompt you each time.

Solution 2:

Here's another possibility using a small Processing program:

String parentFolder = "M:\\INSERT_PARENT_DIR_HERE";

void setup(){
  File fParentFolder = new File(parentFolder);
  println("Scanning " + fParentFolder.getAbsolutePath());
  println("Folder exists: " + fParentFolder.exists());
  File[] folderList = fParentFolder.listFiles();
  println("Number of files/folders: " + folderList.length);
  println("-----------------------------------");
  for(int i=0; i<folderList.length; i++){
    if(folderList[i].isDirectory() && folderList[i].list().length < 2){
      println("Deleting directory: " + folderList[i].getAbsolutePath() + "\t\t" + deleteDir(folderList[i]));  
    } 
  }
}


// Deletes all files and subdirectories under dir.
// Returns true if all deletions were successful.
// If a deletion fails, the method stops attempting to delete and returns false.
public static boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i=0; i<children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    // The directory is now empty so delete it
    return dir.delete();
}