Look for *any* number of files in a folder

This topic contains 6 replies, has 5 voices, and was last updated by Profile photo of Mike Shore Mike Shore 2 years, 6 months ago.

  • Author
    Posts
  • #15479
    Profile photo of Mike Shore
    Mike Shore
    Participant

    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
    Profile photo of Stein Petersen
    Stein Petersen
    Participant

    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.

  • #15483
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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
      Profile photo of Mike Shore
      Mike Shore
      Participant

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

  • #15485
    Profile photo of DJ GRIJALVA
    DJ GRIJALVA
    Participant

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

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

  • #15482
    Profile photo of Mike F Robbins
    Mike F Robbins
    Participant

    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
    Profile photo of Mike F Robbins
    Mike F Robbins
    Participant

    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.