【问题标题】:Powershell Script to count .txt files only in a directoryPowershell脚本仅计算目录中的.txt文件
【发布时间】:2019-07-21 20:24:45
【问题描述】:

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

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

请看下图

U:\TESTING\主文件夹

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

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

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

主文件夹行应该只有 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}

【问题讨论】:

  • -recurse 替换为-file
  • 我已经编辑了整个内容..

标签: powershell powershell-3.0 cmdlets


【解决方案1】:

我找到了以下解决方法

  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. 在 -include 中使用 get-Item 而不是 Get-ChildItem

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

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

$path = "D:\LIVE\*"

 $total = Get-Item $path -include *.txt, *.xml  |Where-Object {$_.LastWriteTime} | Measure-Object | ForEach-Object{$_.Count}

【讨论】:

  • 是的,没有-Recurse -Include 很遗憾不能按预期工作 - 请参阅github.com/PowerShell/PowerShell/issues/3304。两个旁白:Where-Object {$_.LastWriteTime} 是一个空操作,因为根据定义,每个文件在.LastWriteItem 中都有一个(非空)值,当强制转换为布尔值时,计算结果为$true。你可以使用( ... | Measure-Object).Count,而不是ForEach-Object{$_.Count}
  • 我的 -filter 问题仅限于一个参数...当我添加一个参数进行搜索时,它出现异常错误
  • 所以我试图仍然使用-include,你提到使用Get-Item而不是Get-ChildItem,当我这样做时,我遇到了这个错误:找不到接受的位置参数论据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多