我在這個片段中的代碼問題找到一個目錄列表,並與大小的文件夾,但我一直運行到一個錯誤清單目錄的子目錄和大小
$Directory = Read-Host "Enter your directory"
$colItems = (Get-ChildItem $Directory | {$_.Attributes -match 'Directory'} |Measure-Object -Property Length -Sum )
之後增加後位|顯示我開始收到錯誤的尺寸。
我在這個片段中的代碼問題找到一個目錄列表,並與大小的文件夾,但我一直運行到一個錯誤清單目錄的子目錄和大小
$Directory = Read-Host "Enter your directory"
$colItems = (Get-ChildItem $Directory | {$_.Attributes -match 'Directory'} |Measure-Object -Property Length -Sum )
之後增加後位|顯示我開始收到錯誤的尺寸。
Directory對象(DirectoryInfo
類型的對象)沒有length屬性,這就是爲什麼你得到錯誤。爲了獲得由目錄在PowerShell中所佔用的空間,你必須通過遞歸所有的子目錄搜索和添加了所有它們所包含的文件的長度。幸運的是,有幾個來源可以告訴你如何做到這一點。這裏的one.
試試這個
$Folders = Get-ChildItem $Directory | Where-Object {$_.Attributes -eq 'Directory'}
foreach ($Folder in $Folders)
{
$FolderSize = Get-ChildItem $Folder.Fullname -recurse | Measure-Object -property length -sum
$Folder.FullName + " -- " + "{0:N2}" -f ($FolderSize.sum/1MB) + " MB"
}
-Recurse參數可以確保從得到System.IO.DirectoryInfo
您也越來越包含長度屬性System.IO.FileInfo
對象分開。
我也建議,而不是使用
$Folders = Get-ChildItem $Directory | Where-Object {$_.Attributes -eq 'Directory'}
您可以使用:
$Folders = Get-ChildItem $Directory | Where-Object {$_.PSIsContainer -eq $True}
此屬性將可用於其他供應商(註冊表,證書存儲等)爲好。
可以使用Scripting.FileSystemObject的 COM對象的簡單性。
$Directory = Read-Host "Enter your directory"
$fso = New-Object -ComObject Scripting.FileSystemObject
Get-ChildItem -Path $Directory | ? { $_.PSIsContainer } | % { $fso.GetFolder($_.FullName).size/1kb }