尝试使用“dir”命令显示子文件夹和文件的大小。
谷歌搜索“powershell 目录大小”后,我发现了两个有用的链接
这些内容很棒,但我正在寻找类似于“dir”输出的东西,方便且简单,并且我可以在文件夹结构的任何地方使用。
所以,我最终这样做了,任何使它变得简单、优雅、高效的建议。
Get-ChildItem |
Format-Table -AutoSize Mode, LastWriteTime, Name,
@{ Label="Length"; alignment="Left";
Expression={
if($_.PSIsContainer -eq $True)
{(New-Object -com Scripting.FileSystemObject).GetFolder( $_.FullName).Size}
else
{$_.Length}
}
};
谢谢你。
最佳答案
第一个次要模式是避免为每个目录创建一个新的 FileSystemObject。使其成为一个函数并将新对象从管道中拉出。
function DirWithSize($path=$pwd)
{
$fso = New-Object -com Scripting.FileSystemObject
Get-ChildItem | Format-Table -AutoSize Mode, LastWriteTime, Name,
@{ Label="Length"; alignment="Left"; Expression={
if($_.PSIsContainer)
{$fso.GetFolder( $_.FullName).Size}
else
{$_.Length}
}
}
}
如果你想完全避免 COM,你可以像这样使用 PowerShell 计算目录大小:
function DirWithSize($path=$pwd)
{
Get-ChildItem $path |
Foreach {if (!$_.PSIsContainer) {$_} `
else {
$size=0; `
Get-ChildItem $_ -r | Foreach {$size += $_.Length}; `
Add-Member NoteProperty Length $size -Inp $_ -PassThru `
}} |
Format-Table Mode, LastWriteTime, Name, Length -Auto
}
关于powershell - 在 Powershell 中显示具有大小的目录结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3876279/