PowerShell脚本获取目录总大小

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

我该怎么做?

尝试以下

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在当前目录下的所有文件(递归)和总结值。

如果你对包含隐藏和系统文件的大小感兴趣,那么你应该在Get-ChildItem中使用-force参数。

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

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

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

 # 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