获取目录总大小的PowerShell脚本

时间:2009-04-30 20:53:29

标签: windows powershell scripting filesystems sysadmin

我需要递归地获取目录的大小。我必须每个月都这样做,所以我想制作一个PowerShell脚本来完成它。

我该怎么做?

4 个答案:

答案 0 :(得分:23)

尝试以下

function Get-DirectorySize() {
  param ([string]$root = $(resolve-path .))
  gci -re $root |
    ?{ -not $_.PSIsContainer } | 
    measure-object -sum -property Length
}

这实际上会产生一些摘要对象,其中包括项目数。你可以抓住Sum属性,这将是长度之和

$sum = (Get-DirectorySize "Some\File\Path").Sum

编辑为什么这样做?

让我们通过管道的组件来分解它。 gci -re $root命令将递归地从起始$root目录中获取所有项目,然后将它们推送到管道中。因此$root下的每个文件和目录都将通过第二个表达式?{ -not $_.PSIsContainer }。传递给此表达式的每个文件/目录都可以通过变量$_访问。前面的?表示这是一个过滤表达式,意味着只保留满足此条件的管道中的值。 PSIsContainer方法将为目录返回true。所以实际上过滤器表达式只保留文件值。最终的cmdlet度量对象将对管道中剩余的所有值的属性Length的值求和。所以它实际上是为当前目录下的所有文件调用Fileinfo.Length(递归)并对值进行求和。

答案 1 :(得分:3)

如果您想要包含隐藏文件和系统文件的大小,那么您应该将-force参数与Get-ChildItem一起使用。

答案 2 :(得分:3)

以下是获取特定文件扩展名大小的快捷方法:

(gci d:\folder1 -r -force -include *.txt,*.csv | measure -sum -property Length).Sum

答案 3 :(得分:1)

感谢那些发布在这里的人。我采用这些知识创造了这个:

# Loops through each directory recursively in the current directory and lists its size.
# Children nodes of parents are tabbed

function getSizeOfFolders($Parent, $TabIndex) {
    $Folders = (Get-ChildItem $Parent);     # Get the nodes in the current directory
    ForEach($Folder in $Folders)            # For each of the nodes found above
    {
        # If the node is a directory
        if ($folder.getType().name -eq "DirectoryInfo")
        {
            # Gets the size of the folder
            $FolderSize = Get-ChildItem "$Parent\$Folder" -Recurse | Measure-Object -property length -sum -ErrorAction SilentlyContinue;
            # The amount of tabbing at the start of a string
            $Tab = "    " * $TabIndex;
            # String to write to stdout
            $Tab + " " + $Folder.Name + "   " + ("{0:N2}" -f ($FolderSize.Sum / 1mb));
            # Check that this node doesn't have children (Call this function recursively)
            getSizeOfFolders $Folder.FullName ($TabIndex + 1);
        }
    }
}

# First call of the function (starts in the current directory)
getSizeOfFolders "." 0
相关问题