Powershell脚本只计算目录中的.txt文件

问题描述 投票:0回答:1

我的目标是向某些用户发送电子邮件,以通知某些文件夹目录中文件的当前计数。

我只需要使用.txt扩展名来计算文件,并排除其中的文件夹和文件。

请看下面的插图

U:\ TESTING \主文件夹

Testing Main Folder Image

U:\ TESTING \主文件夹\子文件夹1

Testing Sub Folder 1 Image

U:\ TESTING \主文件夹\子文件夹2

Testing Sub Folder 2 Image

输出结果应该看起来像这样

Example output table

主文件夹行应该只有1,但它还包括子文件夹1和2以及其中的txt文件。

以下是计算总文件数的代码部分

$total = Get-ChildItem $path -Recurse -File -Include *.txt |Where-Object {$_.LastWriteTime} | Measure-Object | ForEach-Object{$_.Count}

当我在此行中删除-Recurse时,对于总列,结果变为0

 $total = Get-ChildItem $path  -File -Include *.txt |Where-Object {$_.LastWriteTime} | Measure-Object | ForEach-Object{$_.Count}
powershell powershell-v3.0 cmdlets
1个回答
0
投票

我找到了以下解决方法

  1. 通过使用-filter而不是-include

只需删除-recurse以在计数中排除子目录文件并使用-filter而不是-include

$path = "D:\LIVE"

 $total = Get-ChildItem $path  -File -filter *.txt |Where-Object {$_.LastWriteTime} | Measure-Object | ForEach-Object{$_.Count}
  1. 使用get-Item代替Get-ChildItem和-include

-Filter仅限于使用一个参数,因此如果要使用-include尽可能多地使用搜索参数,请使用Get-Item而不是get-childItem

只需添加*(当没有声明路径时)或*附加到现有路径

$path = "D:\LIVE\*"

 $total = Get-Item $path -include *.txt, *.xml  |Where-Object {$_.LastWriteTime} | Measure-Object | ForEach-Object{$_.Count}
© www.soinside.com 2019 - 2024. All rights reserved.