Look for *any* number of files in a folder

Welcome Forums General PowerShell Q&A Look for *any* number of files in a folder

This topic contains 6 replies, has 5 voices, and was last updated by

 
Participant
4 years, 5 months ago.

  • Author
    Posts
  • #15479

    Participant
    Points: 2
    Rank: Member

    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

    Participant
    Points: 1
    Rank: Member

    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

    Member
    Points: 0
    Rank: Member

    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

      Participant
      Points: 2
      Rank: Member

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

  • #15485

    Participant
    Points: 0
    Rank: Member

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

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

  • #15482

    Participant
    Points: 53
    Rank: Member

    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

    Participant
    Points: 53
    Rank: Member

    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?

The topic ‘Look for *any* number of files in a folder’ is closed to new replies.