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

问题描述

我有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

解决方法

您将关闭,这将使您在任何文件夹C:\ Folder \ Test *下的file.txt文件总数

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

,

如果我对问题的理解正确,则希望获取1级深度的根文件夹中所有* .txt文件的数量,其中直接父文件夹名称称为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”文件。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...