To list only directories that contain items using PowerShell, use the Get-ChildItem cmdlet with the -Directory switch to filter for folders and pipe the results to Where-Object. Inside the filter, check if Get-ChildItem -Path $_.FullName -Force returns any objects. This approach ensures you only see folders that are not empty, effectively solving the problem of filtering out blank directories from your output.
Understanding Get-Childitem Behavior
By default, theGet-ChildItem cmdlet (often aliased as gci, dir, or ls) retrieves all items in a specified location, including files, subdirectories, and registry keys. When navigating complex file systems, this can result in a cluttered output where empty folders take up valuable screen space. While the -Recurse parameter allows you to traverse nested structures, it does not inherently filter out empty containers. Users often find themselves manually scrolling through lists of empty directories, which is inefficient for scripting or quick system audits.
The core challenge lies in the fact that Get-ChildItem treats directories and files similarly when listing contents. Without specific filtering, an empty folder appears just like a populated one in the initial listing phase. To address this, we must introduce a secondary evaluation step that inspects the contents of each directory individually. This requires combining the directory selection capability with a content verification logic.
The Standard Filtering Approach
The most robust method involves chaining commands to first isolate directories and then verify their contents. You start by invokingGet-ChildItem with the -Directory parameter. This restricts the initial scan to folders only, excluding files from the primary dataset. Once you have a collection of directory objects, you pipe them into Where-Object (aliased as where or ?).
Inside the Where-Object script block, you reference the current object using the automatic variable $_. You then call Get-ChildItem again, targeting the full path of the current directory ($_.FullName). It is crucial to include the -Force parameter in this inner call. Without -Force, hidden files and system-level items might be ignored, leading to false negatives where a directory appears empty but actually contains hidden configuration files. The condition checks if the count of returned items is greater than zero. If true, the directory is included in the final output.
Here is the fundamental structure of this command:
Get-ChildItem -Directory | Where-Object {
(Get-ChildItem -Path $_.FullName -Force).Count -gt 0
}
This command is effective because it separates concerns. The first part handles the scope (directories), and the second part handles the state (populated vs. empty). This separation makes the logic easier to read and modify for different requirements.
Optimizing Performance with Recursion
When working with deep directory trees, the standard approach above can be slow. This is because it performs two passes over the data: one to list directories and another to check each one. For large drives, this double traversal can significantly impact performance. A more optimized strategy uses the-Recurse parameter combined with careful filtering.
However, simply adding -Recurse to the outer command will return both files and directories. To fix this, you must ensure that the inner check still respects the directory constraint. Alternatively, you can use a pipeline that filters recursively but evaluates depth. A common pattern involves getting all children recursively, grouping them by parent, and checking if the group has members other than just the container itself. But the simplest recursive optimization is to apply the same logic to every item in the tree.
Get-ChildItem -Recurse -Directory | Where-Object {
(Get-ChildItem -Path $_.FullName -Force -Recurse).Count -gt 0
}
Note that adding -Recurse inside the Where-Object block changes the definition of "items" to include nested subfolders. If you only want to know if a folder has immediate children, remove the inner -Recurse. Choose based on whether you consider a folder "populated" if it contains a single empty subfolder.
Handling Hidden and System Files
A frequent source of confusion is why a directory appears empty in File Explorer but shows up as non-empty in PowerShell, or vice versa. Windows hides certain system files and folders by default. PowerShell also hides these by default unless instructed otherwise. This discrepancy often leads users to believe their filtering logic is broken. To ensure accurate results, always use the-Force flag. This tells PowerShell to reveal hidden files, read-only attributes, and system-marked items. If you omit -Force, you might miss critical data stored in hidden directories, such as user profile configurations or application caches. Conversely, if you want to strictly mimic the visual experience of File Explorer, you could omit -Force, but this is rarely recommended for administrative tasks.
Another consideration is symbolic links. By default, Get-ChildItem may resolve symlinks or treat them differently depending on the version of PowerShell. In PowerShell 5.1 and earlier, symlinks were not fully supported in all contexts. In PowerShell Core (7+), symlink handling is more consistent. If you encounter errors related to access denied, it is often due to trying to read a symlink that points to a restricted area. Using -ErrorAction SilentlyContinue can help suppress these errors during bulk operations.
For more information on moving items while respecting directory constraints, you might find our guide on affecting only directories helpful. See How to affect only directories with Move-Item in PowerShell? for related techniques.
Frequently Asked Questions
Why does my command return empty directories anyway?
This usually happens if you forget to include the -Force parameter. Without it, PowerShell ignores hidden files, making a directory look empty even if it contains system data. Ensure -Force is present in the inner Get-ChildItem call to capture all items.
Can I use aliases to make this command shorter?
Yes, you can use dir or ls instead of Get-ChildItem and ? instead of Where-Object. For example, dir -Directory | ? { (dir $_.FullName -Force).Count -gt 0 }. However, using full cmdlet names improves readability and reduces ambiguity in complex scripts.
How do I exclude specific subdirectories from the check?
You can add a -Exclude parameter to the inner Get-ChildItem call or filter the results before counting. For instance, you can pipe the inner results to another Where-Object clause to remove unwanted paths before checking the count. This prevents excluded folders from contributing to the "populated" status.
Is there a performance difference between checking immediate children vs. all nested items?
Yes. Checking immediate children is much faster because it only scans one level deep. Checking all nested items with -Recurse inside the filter traverses the entire subtree, which is computationally expensive. Use immediate checks for simple presence detection and recursive checks only if you need to know if any descendant exists.
What if I want to delete these populated directories?
You can append | Remove-Item -Recurse -Force to the end of your pipeline. Be extremely cautious when doing this, as it will permanently delete all contents within those directories. Always test the command without the deletion step first to verify the list of targeted folders.