-2

如何以红色显示少于 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  
4

1 回答 1

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 $_
            }
        }
    }
}
于 2018-12-18T15:49:58.373 回答