根据条件以特定颜色显示行

时间:2018-12-18 13:15:55

标签: powershell

如何以红色显示少于20%的自由空间。

PS C:>> $AllServersInfo[0].Disks | Format-Table  

DriveLetter VolumeName Capacity(GB) FreeSpace(GB) % FreeSpace  
----------- ---------- ------------ ------------- -----------  
C:                     99.66        12.85                12.9  
E:          SQL Data   200.00       44.02               22.01  

1 个答案:

答案 0 :(得分:0)

您可以通过捕获字符串中Format-Table的输出来实现。在换行符上进行拆分,然后像这样遍历每行:

# get the table-styled info in a string
$table = $AllServersInfo[0].Disks | Format-Table -AutoSize | Out-String

# do we have a string to work with?
if ([string]::IsNullOrWhiteSpace($table)) {
    Write-Warning 'Empty output for $AllServersInfo[0].Disks'
}
else {
    # split the string on newlines and loop through each line
    $table -split '\r?\n' | ForEach-Object {
        # do not process empty or whitespace-only strings
        if (!([string]::IsNullOrWhiteSpace($_))) {
            # get the last part of each line to capture the value for FreeSpace
            $temp = $_.TrimEnd().Substring($_.Length - 12).TrimStart()
            # test if this represents a number
            if ($temp -match '\d+(?:\.\d+)?$') {
                # and if so, check if it is below the threshold value of 20
                if ([double]$Matches[0] -lt 20) {
                    Write-Host $_ -ForegroundColor Red
                }
                else {
                    Write-Host $_
                }
            }
            else {
                Write-Host $_
            }
        }
    }
}
相关问题