簡體   English   中英

PowerShell 獲取目錄總大小的腳本

[英]PowerShell Script to Get a Directory Total Size

我需要遞歸地獲取目錄的大小。 我每個月都必須這樣做,所以我想制作一個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(遞歸)並對值進行求和。

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

(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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM