PowerShell脚本获取目录总大小
答
请尝试以下
function Get-DirectorySize() {
param ([string]$root = $(resolve-path .))
gci -re $root |
?{ -not $_.PSIsContainer } |
measure-object -sum -property Length
}
这实际上产生了一下汇总对象将包括项目的计数。你可以只抢了总财产,虽然这将是长度
$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
不错。 (Get-DirectorySize“Some \ File \ Path”)。Sum/1mb或(Get-DirectorySize“Some \ File \ Path”)。Sum/1gb转换为megs或gigs。 – aphoria 2009-04-30 22:31:17