首页 > 解决方案 > 测量多个属性?

问题描述

我想使用 Get-ChildItem 查询一个目录,并创建一个包含路径、大小(以 Gb 为单位)、MinimumCreationTime、MaximumCreationTime 等列的表。在 foreach 循环中,我编写了 3 个测量命令。是否可以使用一个命令测量多个属性?

$pathes = @'
C:\open
C:\games
'@.Split([System.Environment]::NewLine, [System.StringSplitOptions]::RemoveEmptyEntries)

foreach ($path in $pathes){
    Get-ChildItem $path -Recurse | Measure Length -Sum 
    Get-ChildItem $path -Recurse | Measure CreationTime -Minimum
    Get-ChildItem $path -Recurse | Measure CreationTime -Maximum
    }

标签: powershellmeasureget-childitempowershell-5.1

解决方案


是否可以使用一个命令测量多个属性?

是的,你可以——只是不是你需要的方式

我们在这里不能完全整合所有三个调用的原因是它将对每个输入属性Measure-Object执行所有请求的计算——并且它不能有意义地计算多个值的总和。[datetime]

所以充其量,我们只需要 2 轮管道就可以做到Measure-Object

$paths = 'C:\open','C:\games'

foreach ($path in $paths){
    # Let's call Get-ChildItem ONCE, and store the result
    $children = Get-ChildItem $path -Recurse 

    # Now let's do our calculations
    $fileSize = $children | Measure Length -Sum 
    $newAndOld = $children | Measure CreationTime -Minimum -Maximum

    # And finally create a new object to hold the details we calculated above
    [pscustomobject]@{
      Path           = $path
      TotalSize      = $fileSize.Sum
      OldestFileTime = $newAndOld.Minimum
      NewestFileTime = $newAndOld.Maximum
    }
}

当显示具有 4 个或更少属性的对象时,PowerShell 将默认为表格格式,因此您可以期望 shell 中的默认输出是这样的(取决于语言环境):

Path      TotalSize OldestFileTime       NewestFileTime
----      --------- --------------       --------------
C:\open  1234567890 1/1/2018 2:00:00 AM  1/31/2021 7:45:00 PM
C:\games 1234567890 1/1/2018 2:00:00 AM  1/31/2021 7:45:00 PM

推荐阅读