繁体   English   中英

powershell 计数已定义子文件夹中已定义文件的数量

[英]powershell count number of defined files in defined subfolder

我有 N 个不同的目录(标题是随机的,字符串中没有测试模式)

C:\Folder\test1\file.txt
C:\Folder\test2\file.txt
...
C:\Folder\testN\file.txt

我想使用powershell计算所有test1..testN子目录中Folder dir中file.txt文件的数量,例如C:\\Folder\\*\\file.txt

我从下面的代码开始,但它计算所有文件

Write-Host ( Get-ChildItem C:\Folder | Measure-Object ).Count;

你能帮忙吗?

更新:我不需要test1...N子文件夹中的 file.txt 文件,只在test1...N文件夹中例如 - C:\\Folder\\*\\file.txt ,但不需要C:\\Folder\\*\\abc\\file.txt

你很接近,这应该让你得到file.txt文件的总数,任何文件夹 C:\\Folder\\Test*

Write-Host ( Get-ChildItem C:\folder\test* -Directory | Get-ChildItem -Include file.txt | Measure-Object ).Count

编辑:我想我现在得到了你想要的。

Clear-Host
$TestPath = "C:\Folder"
$FileCnt = 0

$Dirs = Get-ChildItem -Path "$TestPath" -Directory 
ForEach ($Dir in $Dirs) {
 $FileCnt += (Get-ChildItem -Path "$($($Dir).FullName)\*.*" -Filter "file.txt"  | 
   Measure-Object).count
}
$FileCnt

下面 Pmental 的解决方案更优雅,但这也有效。 HTH

如果我正确理解了这个问题,您想获取根文件夹中所有 *.txt 文件的计数,深度为 1 级,其中直接父文件夹名称称为testXX是序列号)。

你有这样的结构:

C:\FOLDER
+---test1
|   |   file1.txt
|   |
|   \---abc
|           file1.txt
|
+---test2
|       file1.txt
|
\---test3
        file1.txt

为此,您可以使用

(Get-ChildItem -Path 'C:\Folder' -Filter '*.txt' -Depth 1 | 
    Where-Object { $_.Directory.Name -match '^test\d+$' }).Count

在上面的示例结构中返回3

这应该这样做:

(Get-ChildItem C:\Folder -Filter file.txt -File -Recurse -Depth 1 | Measure-Object).Count

或者,如果您只想要来自子文件夹的文本文件而不是来自 C:\\Folder 本身,那么这个:

$Path = 'C:\Folder'
$Files = Get-ChildItem $Path -Filter file.txt -File -Recurse -Depth 1 | 
    Where-Object PSParentPath -notlike "*::$Path"
($Files | Measure-Object).Count

已编辑:已编辑为仅计算“file.txt”文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM