Search code examples
powershelldirectorytemporary

Counting subfolders of a folder


I am trying to delete ASP .NET temporary files creating a PowerShell script. Until now, I managed to find under C:\Windows\Microsoft .NET\Temporary .NET Files files (not folders) older than 60 days and delete them. But my problem now is that under C:\Windows\Microsoft .NET\Temporary .NET Files there is a folder named root. This folder has only one subfolder. What I want is

  • Count how many subfolders exist under root folder.
  • If there is only one folder, do not do anything.
  • If there are more than one, leaves the most recent folder and delete the others.

How could this be done with PowerShell?


Solution

  • Recurse into that root folder, filter the results for directories (items for which the PSIsContainer property is $true), and count the results:

    Get-ChildItem 'C:\path\to\root' -Recurse |
      ? { $_.PSIsContainer } |
      Measure-Object |
      select -Expand Count
    

    If you have PowerShell v3 or newer you can simplify that by calling Get-ChildItem with the parameter -Directory:

    Get-ChildItem 'C:\path\to\root' -Recurse -Directory |
      Measure-Object |
      select -Expand Count