I'm working on adapting part of a powershell script to a WPF C# windows service and I'm having trouble finding a way to get the last installed windows update like the following script does. I need a way to check that a workstation has installed windows updates in the last 30 days, if it has it passes the audit if not it fails the audit.
$today = Get-Date
$session = (New-Object -ComObject 'Microsoft.Update.Session')
$lastUpdate = ($session.QueryHistory("",0,100) | Where-Object
{$_.ResultCode -eq 2}).Date | Sort-Object -descending
$compInfo = Get-ComputerInfo | select WindowsProductName, WindowsVersion
$OSversion = ($compInfo.WindowsProductName + " " + $compInfo.WindowsVersion).replace("Windows ","")
if (!$lastUpdate) {
$never = $true
$lastUpdate = Get-Date -Year 0001 -Month 01 -Day 01 -Hour 00 -Minute 00 -Second 00
} else {
# Convert from UTC to timezone
$timediff = [int]((Get-Timezone | select BaseUtcOffset | Out-String -Stream)[3][2].ToString())
$lastUpdate = $lastUpdate[0].AddHours(-$timediff)
}
# Audit result
if ($never -or [datetime]$lastUpdate -le ($today.AddDays(-30))) {
# Audit fail
$pass = $false
if ($never) {
$lastUpdate = "Never"
} else {
$lastUpdate = [string]$lastUpdate
}
} else {
# Audit pass
}
I've been reading about the WUApi, but have not been able to get any variation of the following code to not produce errors when trying to use the IUpdateSearcher class. I've tried different namespaces an such and still haven't had any luck.
using WUApiLib;
UpdateSessionClass uSession = new UpdateSessionClass();
IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher();
ISearchResult uResult = uSearcher.Search("IsInstalled=0 and Type='Software'");
It doesn't seem like I will be able to replicate the powershell version exactly, but from what I've researched on the WUAPI I could just check if the computer has any updates that haven't been installed and assign a pass if there are no updates and fail if there are.