[英]PowerShell Script to Get a Directory Total Size
請嘗試以下方法
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(遞歸)並對值進行求和。
以下是獲取特定文件擴展名大小的快捷方法:
(gci d:\folder1 -r -force -include *.txt,*.csv | measure -sum -property Length).Sum
如果您想要包含隱藏文件和系統文件的大小,那么您應該將-force參數與Get-ChildItem一起使用。
感謝那些發布在這里的人。 我采用這些知識創造了這個:
# 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
要通過@JaredPar 改進此答案以進行擴展和提高性能:
function Get-DirectorySize() {
param ([string]$root = $(Resolve-Path .))
Get-ChildItem $root -Recurse -File |
Measure-Object -Property Length -Sum |
Select-Object -ExpandProperty Sum
}
或者,為了更方便地使用探索類型數據:
Update-TypeData -TypeName System.IO.DirectoryInfo -MemberType ScriptProperty -MemberName Size -Value {
Get-ChildItem $this -Recurse -File |
Measure-Object -Property Length -Sum |
Select-Object -ExpandProperty Sum
}
然后使用Get-ChildItem | Select-Object Name,Length,Size
Get-ChildItem | Select-Object Name,Length,Size
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.