且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Powershell中比较文件夹大小

更新时间:2022-06-21 23:55:40

最简单的方法是使用 FileSystemObject COM 对象:

The simplest way is to use the FileSystemObject COM object:

function Get-FolderSize($path) {
    (New-Object -ComObject 'Scripting.FileSystemObject').GetFolder($path).Size
}

不过,我建议不要在 Get-Size 函数中进行格式化.通常***让函数返回原始大小,并在实际显示值时进行计算和格式化.

I'd recommend against doing formatting in a Get-Size function, though. It's usually better to have the function return the raw size, and do calculations and formatting when you actually display the value.

像这样使用它:

Get-ChildItem 'D:\home' | Where-Object {
    $_.PSIsContainer -and
    Get-FolderSize $_.FullName -gt 600MB
}

或者像这样:

Get-ChildItem 'D:\home' | Where-Object {
    $_.PSIsContainer
} | ForEach-Object {
    if (Get-FolderSize $_.FullName -gt 600MB) {
        'Not OK.'
    } else {
        'OK template.'
    }
}

在 PowerShell v3 和更新版本中,您可以使用 Get-ChildItem -Directory 而不是 Get-ChildItem |Where-Object { $_.PSIsContainer }.

On PowerShell v3 and newer you can use Get-ChildItem -Directory instead of Get-ChildItem | Where-Object { $_.PSIsContainer }.