Look for *any* number of files in a folder

I wrote a simple function that looks for and deletes empty folders. I only look for the presence of files, and ignore empty subfolders.

$files = Get-ChildItem -Path $folder -File -Recurse
if ($files.count -gt 0) {Remove-Item $folder -Recurse -Force}

The problem is that for folders with thousands of files, the Get-ChildItem cmdlet takes a long time to run. All I want to know is “are there more than zero files” and I don’t care about the actual number of files. Is there a simpler method?

Hi.

If you don’t want to collect info for all files you could try and wrap the Get-ChildItem in a foreach loop and exit it once you find a single file.

If you’re just going to remove it anyway, why not just cut to the chase and try to remove it, suppressing the error if it doesn’t exist?


Remove-Item $folder -Recurse -Force -ErrorAction SilentlyContinue

In PowerShell 3.0 or later, I’d simply pipe Get-ChildItem to Select-Object -First 1. This will abort the pipeline as soon as one object is found. In PowerShell 2.0, however, this wouldn’t help, and I would probably wind up using a little bit of p/invoke to get at the Win32 API’s FindFirstFile function.

The text portion of the original post says you’re deleting empty folders, but the code appears to delete folders that aren’t empty (delete where greater than 0 files). Could you clarify the objective?

You can also use the .Net method instead of Get-ChildItem which is always faster.

Ah, the -First operator is exactly what I was looking for, thanks!