您可以通过捕获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 $_
}
}
}
}