Author Posts

May 21, 2014 at 12:33 pm

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?

May 21, 2014 at 1:05 pm

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.

May 21, 2014 at 1:13 pm

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

May 21, 2014 at 1:14 pm

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.

May 21, 2014 at 1:20 pm

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?

May 21, 2014 at 1:24 pm

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

[System.IO.Directory]::GetFiles($Path,"*",'AllDirectories')

May 21, 2014 at 2:02 pm

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