powershell - 测量多个属性?
问题描述
我想使用 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
}
解决方案
是否可以使用一个命令测量多个属性?
是的,你可以——只是不是你需要的方式。
我们在这里不能完全整合所有三个调用的原因是它将对每个输入属性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
推荐阅读
- javascript - jQuery 显示/隐藏多个 div
- google-maps - 如何在谷歌地图信息框中插入部分和超链接
- docker - 在 GoCD-Agent 中实现 DooD(Docker 之外的 Docker)
- phpunit - 如何使 PHPUnit 部分重新生成代码覆盖率 HTML 日志
- reactjs - Service Worker OneSignal 冲突 React PWA
- python - 将所有列从 int64 转换为 int32
- unix - Unix 有没有办法用单个命令在两台服务器之间发送文件?
- ios - NavigationController 在 push 和 pop 后会切掉阴影吗?
- spring - 如何从 Open API 3 规范全局忽略 Spring Boot 的 API?
- ios - 如何预加载 SCNAudioSource 以防止第一次播放声音时出现延迟?