Powershell - get-childitem but only return directories that have items in them

Abstract: Filter out empty directories from PowerShell Get-ChildItem output to display only folders containing items.

Created: 2026-10-12 by

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, the Get-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 invoking Get-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.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More