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

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

本文介绍了如何在Powershell中比较文件夹大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果文件夹大小大于或等于 600MB,我必须应用命令.

I have to apply a command IF the folder size is greater or equal to 600MB.

我试过这样的事情

$folders = Get-ChildItem d:\home -exclude *.*
function Get-Size
{
 param([string]$pth)
 "{0:n2}" -f ((gci -path $pth -recurse | measure-object -property length -sum).sum /1mb)
}


ForEach ($subFolder in $folders){

echo $subFolder | select-object fullname
$size = Get-Size $subFolder
echo $size

    if ($size -gt "600") { echo "Not ok." }
    else { echo "OK template." }

}

它不起作用.它写入正确大小的文件夹,但不遵守 IF 语句.我该怎么办?

It doesn't work. It writes the right size of the folder but the IF statement is not respected. How do I do?

推荐答案

最简单的方法是使用 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 }.

这篇关于如何在Powershell中比较文件夹大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 00:22