I have a basic command I'm using to check around 100 servers for the last 5 updates and return their installed date. I'd like to get the script to return the line in red if the installed date is blank.
The command is
Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName $ComputerName | Select-object -Property PSComputerName, @{n='HotFix ID';e={$_.hotfixid}}, @{n='Installation Date';e={$_.installedon}} | select -Last 05
I tried to use format-color but it wouldn't work. The output of the command looks like this
PSComputerName HotFix ID Installation Date
-------------- --------- -----------------
DC1 KB4132216 10/6/2021 12:00:00 AM
DC1 KB4535680 11/3/2021 12:00:00 AM
DC1 KB4589210
DC1 KB5005698 10/6/2021 12:00:00 AM
DC1 KB5007192 11/16/2021 12:00:00 AM
The line without a date I'd like to be red. Is this possible?
Thank you!
CodePudding user response:
A couple of comments regarding your script
You are using
Select -last 05
but the wmi command you ran won't gave you the items in anInstalledOn
ascending order. The 5 items you get are the last 5, but not from a sorted perspective.You can combine your 2 select statements for efficiency purposes (eg:
Select -Last 5 -Property ...
Now, for your actual problem, I would go with vt escape characters.
Here's a modified script that account for all of that.
$ComputerName = 'localhost'
$HotFixes = Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName $ComputerName
$ColoringCondition = {
Param($Value)
$e = [char]27 # For PS 5.1 ... In PS 7.0 , this can be removed and occurences of $e below replaced by `e
if ([String]::IsNullOrEmpty($_.'InstalledOn')) {
return "$e[5;31m$($Value)$e[0m";
}
return $Value
}
$Last5 = $HotFixes | Sort-Object -Property installedon -Descending |
Select -First 5 -Property @{'Name' = 'PSComputerName' ; 'Expression' = { . $ColoringCondition($_.PSComputerName) } },
@{n = 'HotFix ID'; e = { . $ColoringCondition($_.hotfixid) } },
@{n = 'Installation Date'; e = { . $ColoringCondition($_.installedon) } }
$Last5 # Print output
Output
Updates have been sorted by
InstalledOn
property (Descending so that the most recent is displayed first) and because of that sort, we select the 5 first item (5 most recent)A coloring condition is checked against all the properties and if the installation date is missing, the coloring is added to the cell value of the line.
Note:
If you are using Powershell 7 , you do not have to declare $e = [char]27
and you can simply use `e (backtick e) instead.
Note 2:
As a byproduct of the initial sorting (sort by installation date, descending), this mean that all the updates with an empty installation date will go to the bottom and likely never get selected by the top 5. I'd think that if they have an empty installation date, they might be updates that came in with the system and can safely be ignored but that is something to keep in mind.
References:
Console Virtual Terminal Sequences - Text formatting