仅在目录中计算 .txt 文件的 Powershell 脚本 [英] Powershell Script to count .txt files only in a directory
问题描述
我的目标是向某些用户发送电子邮件,以通知某些文件夹目录中的当前文件数.
My goal is to send email to some users to notify about the current count of the files inside some folder directories.
我只需要计算扩展名为 .txt 的文件并排除其中的文件夹和文件.
I need to count files only with .txt extensions and exclude folders and files inside this.
请看下图
U:\TESTING\Main 文件夹
U:\TESTING\Main Folder\Sub Folder 1
U:\TESTING\Main Folder\Sub Folder 2
输出结果应该是这样的
主文件夹行应该只有 1,但它还包括子文件夹 1 和 2 以及其中的 txt 文件.
这是计算文件总数的部分代码
$total = Get-ChildItem $path -Recurse -File -Include *.txt |Where-Object {$_.LastWriteTime} | Measure-Object | ForEach-Object{$_.Count}
当我在这一行中删除 -Recurse 时,总列的结果变为 0
When I remove -Recurse in this line, the result becomes 0 for total column
$total = Get-ChildItem $path -File -Include *.txt |Where-Object {$_.LastWriteTime} | Measure-Object | ForEach-Object{$_.Count}
推荐答案
我找到了以下解决方法
I found the following workaround
- 使用 -filter 而不是 -include
只需删除 -recurse 即可排除子目录文件并使用 -filter 而不是 -include
just remove the -recurse to exclude subdirectories files in counting and use -filter instead of -include
$path = "D:\LIVE"
$total = Get-ChildItem $path -File -filter *.txt |Where-Object {$_.LastWriteTime} | Measure-Object | ForEach-Object{$_.Count}
- 使用带有 -include 的 get-Item 而不是 Get-ChildItem
-Filter 仅限于使用一个参数,因此如果您想使用 -include 来使用尽可能多的搜索参数,请使用 Get-Item 而不是 get-childItem
-Filter is limited to using one paramter, so if you want to use -include to use as many searching parameter as you can, use Get-Item instead of get-childItem
只需添加 *(当未声明路径时)或 * 附加到现有路径
just add * (when no path is declared) or * appending to the existing path
$path = "D:\LIVE\*"
$total = Get-Item $path -include *.txt, *.xml |Where-Object {$_.LastWriteTime} | Measure-Object | ForEach-Object{$_.Count}
这篇关于仅在目录中计算 .txt 文件的 Powershell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!