簡體   English   中英

PowerShell sort在某些機器上可以正常運行,但在其他機器上則不能

[英]PowerShell sort works fine on some machines but not others

我不太熟悉PowerShell,並且一直在嘗試對以下代碼的輸出進行排序:

function Get-DirSize ($path) { 

    BEGIN {} 

    PROCESS{ 
        $colItems = Get-ChildItem $path | Where-Object {$_.PSIsContainer -eq $true} | Sort-Object

        foreach ($folder in $colItems)
        {
            $object = New-Object -TypeName PSObject 
            $subFolderItems = Get-ChildItem $folder.FullName -recurse -force -ErrorAction SilentlyContinue | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
            $sizeGB="{0:N4}" -f ($subFolderItems.sum/1GB)   
            $object | Add-Member -MemberType NoteProperty -Name "Folder" -Value $folder.FullName
            $object | Add-Member -MemberType NoteProperty -Name "Size(GB)" -Value $sizeGB 
            $object 
        } 
    }
    END {} 
}

Get-DirSize -path 'C:\' |
Sort-Object 'Size(GB)' -Descending

我可以在台式機上獲得排序的輸出,但是不知何故,相同的代碼也無法在筆記本電腦上為我提供排序的輸出(如下所示,為筆記本電腦的輸出)。

PSSortedOutput

有誰知道為什么會這樣? 還是我應該對代碼本身進行更改。

謝謝。

這行:

$sizeGB="{0:N4}" -f ($subFolderItems.sum/1GB)

($subFolderItems.sum/1GB)轉換為字符串,並將其存儲在名為“ sizeGB”的變量中。

然后在這一行:

Sort-Object 'Size(GB)' -Descending

您正在按降序對該字符串排序。 因此,您正在對數字字符串進行詞法排序(又稱字母順序)。 如果查看結果,您會發現它們按字母順序降序排列(例如,以“ 6”開頭的字符串在以“ 5”開頭的字符串之前,以“ 4”開頭的字符串等等)。

因此,請勿過早將數字轉換為字符串以進行格式化。 無論如何,格式化從函數返回的對象都與PowerShell的想法相反。 您想要從頭到尾一直處理對象。 最終使用者應該是決定如何格式化輸出的使用者。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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