我正在檢查我的服務器磁盤空間使用情況並生成一個文本文件作爲報告。 我想按照FreePercentage Free%的升序對輸出文件進行排序。如何在PowerShell中對文本文件進行排序
我被困在這個階段。它只是不排序。 它是一個分隔符問題?我的錯誤在哪裏?
# files to be used
$FileName0 = "C:\MONITORING\WINDOWS-SPACE\SCRIPT\SPACE0.txt"
$FileName1 = "C:\MONITORING\WINDOWS-SPACE\SCRIPT\SPACE1.txt"
$FileName2 = "C:\MONITORING\WINDOWS-SPACE\SCRIPT\SPACE2.txt"
# file containing servers list
#$ServerName = Get-Content "C:\MONITORING\WINDOWS-SPACE\SCRIPT\COMPUTERS.txt"
# use 2 servers only for coding test, will be replaced by a file containing all
# servers
$ServerName = "SERVER1","SERVER2"
# loop and process drive-id and calculations and populate filename-0
foreach ($_ in $ServerName) {
Get-WmiObject -Query "Select * from win32_logicaldisk" -ComputerName $_ |
Select PSComputername, DeviceID,
@{Name="TotalGB"; Expression={"{0:N0}" -F ($_.Size/1GB)}},
@{Name="UsedGB" ; Expression={"{0:N0}" -F (($_.Size/1GB)-($_.Freespace/1GB))}},
@{Name="FreeGB" ; Expression={"{0:N0}" -F ($_.Freespace/1GB)}},
@{Name="Free%" ; Expression={"{0:N0}" -F (($_.Freespace/$_.Size)*100)}} |
Format-Table -AutoSize >> $FileName0
}
# remove unwanted drives ('A'&'Z') and duplicate lines and empty lines and
# populate filename-1
Get-Content $FileName0 | Select-Object -Unique |
Where {$_ -notmatch "A:"} |
Where {$_ -notmatch "Z:"} |
Where { $_ -notmatch "^-" } |
Where {$_ -ne ""} |
Format-Table -AutoSize > $FileName1
# input final result into a CSV file filename-2
Import-Csv $FileName1 -Header PSComputername, TotalGB, UsedGB, FreeGB, Free% |
sort [int]Free% |
Format-Table -AutoSize >> $FileName2
實際輸出文件:
PSComputerName DeviceID TotalGB UsedGB FreeGB Free% SERVER1 C: 60 33 27 45 SERVER1 D: 20 2 18 88 SERVER2 C: 40 27 13 33 SERVER2 D: 50 6 44 87
所需的輸出文件:
PSComputerName DeviceID TotalGB UsedGB FreeGB Free% SERVER2 C: 40 27 13 33 SERVER1 C: 60 33 27 45 SERVER2 D: 50 6 44 87 SERVER1 D: 20 2 18 88
我能說什麼?這是完美!非常感謝 !!! – user270488
'FreePercent'是字符串值,所以你需要'Sort-Object {[int] $ _。FreePercent}'以正確的順序得到結果。 –
正確,我注意到在我發佈並更新後將所有值轉換爲'[Int]'。 –