Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting folders with Powershell

Does anybody know a powershell 2.0 command/script to count all folders and subfolders (recursive; no files) in a specific folder ( e.g. the number of all subfolders in C:\folder1\folder2)?

In addition I also need also the number of all "leaf"-folders. in other words, I only want to count folders, which don't have subolders.

like image 661
M. X Avatar asked Oct 17 '12 12:10

M. X


People also ask

How do I count number of folders?

To count all the files and directories in the current directory and subdirectories, type dir *. * /s at the prompt.

How do I count files in PowerShell?

To get count files in the folder using PowerShell, Use the Get-ChildItem command to get total files in directory and use measure-object to get count files in a folder.

What command is used to count number of folders?

Using the ls Command. The ls command lists the directories and files contained in a directory. The ls command with the -lR options displays the list (in long format) of the sub-directories in the current directory recursively.

Is there a way to count the number of files in a folder?

To determine how many files there are in the current directory, put in ls -1 | wc -l. This uses wc to do a count of the number of lines (-l) in the output of ls -1. It doesn't count dotfiles.


2 Answers

In PowerShell 3.0 you can use the Directory switch:

(Get-ChildItem -Path <path> -Directory -Recurse -Force).Count
like image 114
Shay Levy Avatar answered Oct 12 '22 21:10

Shay Levy


You can use get-childitem -recurse to get all the files and folders in the current folder.

Pipe that into Where-Object to filter it to only those files that are containers.

$files = get-childitem -Path c:\temp -recurse 
$folders = $files | where-object { $_.PSIsContainer }
Write-Host $folders.Count

As a one-liner:

(get-childitem -Path c:\temp -recurse | where-object { $_.PSIsContainer }).Count
like image 31
RB. Avatar answered Oct 12 '22 19:10

RB.