使用PowerShell计算文件夹中的项目

Hyd*_*per 77 powershell-2.0

我正在尝试编写一个非常简单的PowerShell脚本来为我提供给定文件夹(c:\MyFolder)中项目(文件和文件夹)的总数.这就是我所做的:

Write-Host ( Get-ChildItem c:\MyFolder ).Count;
Run Code Online (Sandbox Code Playgroud)

问题是,如果我有1或0项,命令不起作用 - 它什么都不返回.

有任何想法吗?

小智 131

你应该Measure-Object用来计算东西.在这种情况下,它看起来像:

Write-Host ( Get-ChildItem c:\MyFolder | Measure-Object ).Count;
Run Code Online (Sandbox Code Playgroud)

或者如果那太长了

Write-Host ( dir c:\MyFolder | mo).Count;
Run Code Online (Sandbox Code Playgroud)

并在PowerShell 4.0中使用measure别名而不是mo

Write-Host (dir c:\MyFolder | measure).Count;
Run Code Online (Sandbox Code Playgroud)


Hyd*_*per 33

我终于找到了这个链接:

https://blogs.perficient.com/microsoft/2011/06/powershell-count-property-returns-nothing/

好吧,事实证明这是一个怪癖,正是因为目录中只有一个文件.一些搜索显示,在这种情况下,PowerShell返回标量对象而不是数组.此对象没有count属性,因此无需检索任何内容.

解决方案 - 强制PowerShell返回带有@符号的数组:

Write-Host @( Get-ChildItem c:\MyFolder ).Count;
Run Code Online (Sandbox Code Playgroud)

  • 很好,谢谢.当命令行程尝试并"有用"并改变其返回类型时,我觉得很烦人. (3认同)

小智 30

如果你需要加快这个过程(例如计算30k或更多的文件),那么我会选择这样的东西.

$filepath = "c:\MyFolder"
$filetype = "*.txt"
$file_count = [System.IO.Directory]::GetFiles("$filepath", "$filetype").Count
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用 `[System.IO.Directory]::GetFiles("$filepath", "$filetype",1)` 递归此操作,请参阅[此处](https://docs.microsoft.com/en-us/dotnet /api/system.io.directory.getfiles?view=netframework-4.8) (2认同)

dhc*_*cgn 12

只有文件

Get-ChildItem D:\ -Recurse -File | Measure-Object | %{$_.Count}
Run Code Online (Sandbox Code Playgroud)

只有文件夹

Get-ChildItem D:\ -Recurse -Directory | Measure-Object | %{$_.Count}
Run Code Online (Sandbox Code Playgroud)

Get-ChildItem D:\ -Recurse | Measure-Object | %{$_.Count}
Run Code Online (Sandbox Code Playgroud)

  • @AlLelopath``Get-ChildItem D:\ -Recurse -File -Include*.jpg,*.png | 测量对象| %{$ _.数}`` (4认同)
  • 在第一个,我将如何搜索所有jpg和png文件? (2认同)

小智 9

您还可以使用别名

(ls).Count
Run Code Online (Sandbox Code Playgroud)