Look for *any* number of files in a folder

This topic contains 6 replies, has 5 voices, and was last updated by  Mike Shore 4 years ago.

  • Author
  • #15479

    Mike Shore

    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?

  • #15481

    Stein Petersen


    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.

  • #15483

    Dave Wyatt

    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.

    • #15486

      Mike Shore

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

  • #15485


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


  • #15482

    Mike F Robbins

    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
  • #15484

    Mike F Robbins

    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 must be logged in to reply to this topic.