【问题标题】:With PowerShell's Get-ChildItem, how to I list matching files AND count them at the same time使用 PowerShell 的 Get-ChildItem,我如何列出匹配的文件并同时计算它们
【发布时间】:2019-11-25 05:27:54
【问题描述】:

如何在 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}

【问题讨论】:

  • 简单地将所有匹配项存储在一个变量$t = Get-ChildItem -Path $searchLocation -Filter $filename -Recurse -ErrorAction SilentlyContinue; $t.Count; $t.FullName

标签: powershell get-childitem


【解决方案1】:

由于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}

【讨论】:

    【解决方案2】:

    另一种方法是在处理每个文件时为其添加一个文件编号。

    $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 获取最后一个文件编号。并且它将保持所有额外的文件元数据像CreationTimeDirectoryNameVersionInfo 等一样烂。

    【讨论】:

    • 我的解决方案是一样的 ;)
    【解决方案3】:

    就像这样:

    $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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-21
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多