如何在PowerShell中使用单个Get-ChildItem命令显示和计数匹配文件?当前,我正在使用两个Get-ChildItem命令,第一个用于计数,第二个用于显示文件-可以正常工作,但在扫描整个磁盘时效果不佳...
用于计算比赛次数的命令:$count = Get-ChildItem -Path $searchLocation -Filter $filename -Recurse -ErrorAction SilentlyContinue | Measure-Object | %{$_.Count}
显示文件的命令:Get-ChildItem -Path $searchLocation -Filter $filename -Recurse -ErrorAction SilentlyContinue | %{$_.FullName}
由于Get-ChildItem
返回一个数组,其大小存储在.Length
成员中,因此不需要显式测量。因此,将文件名存储在同一集合中,然后打印长度以输入条目数,然后对集合进行迭代以获取文件名。将变量名交换为$files
即可反映出来,
$files = Get-ChildItem -Path $searchLocation -Filter $filename `
-Recurse -ErrorAction SilentlyContinue
# ` can used to divide command into multiple lines (and work-around for markup stupidness)
# prints the number of items
$files.Length
# prints the full names
$files | %{$_.FullName}
[一种替代方法是在处理每个文件时向其添加文件编号。
$i = 1
$Files = Get-ChildItem -Path $searchLocation -Filter $filename -Recurse -ErrorAction SilentlyContinue
Foreach($Item in $Files) {
$Item | Add-Member -MemberType NoteProperty -Name FileNo -Value $i
$i++
}
$Files | Select-Object FileNo, Fullname
然后,您可以查看文件的处理顺序,并通过执行$File[-1].FileNo
得到最后一个文件号。并且它将保持所有其他文件元数据吸收为CreationTime
,DirectoryName
,VersionInfo
等
简单这样:
$AllFile=Get-ChildItem $searchLocation -File -Filter $filename -Recurse | select FullName
$AllFile.Count
$AllFile.FullName
或者您可以像这样在您的循环中添加排名:
$Rang=0
Get-ChildItem "c:\temp" -File -Filter "*.txt" -Recurse | %{
$Rang++
Add-Member -InputObject $_ -Name "Rang" -MemberType NoteProperty -Value $rang
$_
} | select Rang, FullName