Counting folders with Powershell

2019-04-28 10:49发布

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.

6条回答
做自己的国王
2楼-- · 2019-04-28 11:43

To answer the second part of your question, of getting the leaf folder count, just modify the where object clause to add a non-recursive search of each directory, getting only those that return a count of 0:

(dir -rec | where-object{$_.PSIsContainer -and ((dir $_.fullname | where-object{$_.PSIsContainer}).count -eq 0)}).Count

it looks a little cleaner if you can use powershell 3.0:

(dir -rec -directory | where-object{(dir $_.fullname -directory).count -eq 0}).count
查看更多
啃猪蹄的小仙女
3楼-- · 2019-04-28 11:44

Get the path child items with recourse option, pipe it to filter only containers, pipe again to measure item count

((get-childitem -Path $the_path -recurse | where-object { $_.PSIsContainer }) | measure).Count
查看更多
萌系小妹纸
4楼-- · 2019-04-28 11:47

Another option:

(ls -force -rec | measure -inp {$_.psiscontainer} -Sum).sum
查看更多
老娘就宠你
5楼-- · 2019-04-28 11:50

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
查看更多
Deceive 欺骗
6楼-- · 2019-04-28 11:52

In PowerShell 3.0 you can use the Directory switch:

(Get-ChildItem -Path <path> -Directory -Recurse -Force).Count
查看更多
ら.Afraid
7楼-- · 2019-04-28 11:52

This is a pretty good starting point:

(gci -force -recurse | where-object { $_.PSIsContainer }).Count

However, I suspect that this will include .zip files in the count. I'll test that and try to post an update...

EDIT: Have confirmed that zip files are not counted as containers. The above should be fine!

查看更多
登录 后发表回答