PowerShell脚本获取目录总大小 [英] PowerShell Script to Get a Directory Total Size

查看:617
本文介绍了PowerShell脚本获取目录总大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

>

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

将包括项目的计数的摘要对象的位。你可以直接抓住Sum属性,这将是长度的总和。

$ $ $ $ $ $ $ $ = $ Get = \File\Path)。Sum

编辑工作?

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


I need to get the size of a directory, recursively. I have to do this every month so I want to make a PowerShell script to do it.

How can I do it?

解决方案

Try the following

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

This actually produces a bit of a summary object which will include the Count of items. You can just grab the Sum property though and that will be the sum of the lengths

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

EDIT Why does this work?

Let's break it down by components of the pipeline. The gci -re $root command will get all items from the starting $root directory recursively and then push them into the pipeline. So every single file and directory under the $root will pass through the second expression ?{ -not $_.PSIsContainer }. Each file / directory when passed to this expression can be accessed through the variable $_. The preceding ? indicates this is a filter expression meaning keep only values in the pipeline which meet this condition. The PSIsContainer method will return true for directories. So in effect the filter expression is only keeping files values. The final cmdlet measure-object will sum the value of the property Length on all values remaining in the pipeline. So it's essentially calling Fileinfo.Length for all files under the current directory (recursively) and summing the values.

这篇关于PowerShell脚本获取目录总大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆