我正在尝试编写一个非常简单的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)
小智 30
如果你需要加快这个过程(例如计算30k或更多的文件),那么我会选择这样的东西.
$filepath = "c:\MyFolder"
$filetype = "*.txt"
$file_count = [System.IO.Directory]::GetFiles("$filepath", "$filetype").Count
Run Code Online (Sandbox Code Playgroud)
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)
| 归档时间: |
|
| 查看次数: |
157669 次 |
| 最近记录: |