PowerShell Script to Get a Directory Total Size

后端 未结 4 1362
情话喂你
情话喂你 2021-02-05 09:45

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?

4条回答
  •  遥遥无期
    2021-02-05 10:32

    Thanks to those who posted here. I adopted the knowledge to create this:

    # 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
    

提交回复
热议问题