windows 使用 Powershell 计算文件夹
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12934106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Counting folders with Powershell
提问by M. X
Does anybody know a powershell 2.0command/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)?
有没有人知道一个powershell 2.0命令/脚本来计算特定文件夹中的所有文件夹和子文件夹(递归;没有文件)(例如,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.
此外,我还需要所有“叶”文件夹的数量。换句话说,我只想计算没有子目录的文件夹。
回答by RB.
You can use get-childitem -recurse
to get all the files and folders in the current folder.
您可以使用get-childitem -recurse
获取当前文件夹中的所有文件和文件夹。
Pipe that into Where-Object
to filter it to only those files that are containers.
通过管道将Where-Object
其过滤到仅作为容器的文件。
$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
回答by Shay Levy
In PowerShell 3.0 you can use the Directory switch:
在 PowerShell 3.0 中,您可以使用目录开关:
(Get-ChildItem -Path <path> -Directory -Recurse -Force).Count
回答by walid2mi
Another option:
另外一个选项:
(ls -force -rec | measure -inp {$_.psiscontainer} -Sum).sum
回答by Dan Puzey
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...
但是,我怀疑这将包括.zip
计数中的文件。我会测试并尝试发布更新...
EDIT:Have confirmed that zip files are notcounted as containers. The above should be fine!
编辑:已确认 zip 文件不计为容器。以上应该没问题!
回答by zdan
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:
要回答问题的第二部分,即获取叶文件夹计数,只需修改 where object 子句以添加对每个目录的非递归搜索,仅获取返回计数为 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:
如果您可以使用 powershell 3.0,它看起来会更干净一些:
(dir -rec -directory | where-object{(dir $_.fullname -directory).count -eq 0}).count
回答by Pierluigi
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