(抱歉,如果标题不是最好的,我不知道如何写我的意思)
您好,我对 PowerShell 有点陌生,但我想创建一个函数,只要我想查看当前目录中每个文件夹的大小,就可以运行该函数。 我发现下面的代码看起来与我需要的完全一样..但是,无论我将
Sort-Object
放在哪里,它都不会排序任何内容。我确信这是用户错误,因为我以前从未真正使用过 Sort-Object,而且我在网上没有找到太多信息,所以我决定只是问问。
function Print-Sizes {
$colItems = Get-ChildItem $startFolder | Where-Object {$_.PSIsContainer -eq $true}
foreach ($i in $colItems)
{
$subFolderItems = Get-ChildItem $i.FullName -recurse -force | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
'{0:N2}' -f ($subFolderItems.sum / 1MB) + ' MB' + ' | ' + $i.Name
}
}
这放置在
Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
文件中。
正如我所提到的,我尝试添加
Sort-Items -Property Length
但无论我将其插入何处,它都不会对 Powershell 打印的内容进行排序。
我想知道我做了什么/做错了什么。
提前谢谢您!
由于代码中的 foreach 循环输出格式化为 strings,因此不再有具有 Length 属性的对象可供排序。
假设您的变量
$startFolder
在调用函数之前已在某处定义,我会将其更改为如下所示
function Print-Sizes {
$colItems = Get-ChildItem -Path $startFolder -Directory
# loop over the subfolders and collect objects with properties Size and Name
$result = foreach ($folder in $colItems) {
$size = (Get-ChildItem -Path $folder.FullName -Recurse -Force -File |
Measure-Object -Property Length -Sum).Sum
# output a custom object for each subfolder
[PsCustomObject]@{
Size = [Math]::Round($size / 1MB, 2) # store numerical [double] values, not formatted strings
Name = $folder.Name
}
}
# sort on Size property
$result | Sort-Object -Property Size
}
输出看起来像这样
Size Name
---- ----
44,83 Folder1
125,99 Folder2
277,82 Folder3
841,24 Folder Etcetera
5520,33 PowerShell
附注我的系统是荷兰语,所以这里的小数点是逗号