how to get the last windows update dates in VCenter

61 Views Asked by At

I would like to write a script and then automate it to check weekly the Windows updates of VMs in Vcenter and note the date, if a machine has not update Windows for more than 90 days, send a mail. However, I am currently really stucked and do not know how to proceed, I have the following script ready written, but it does not work due to so-called no permission, although my user is fully Admin in VCenter. can you help me further?

CLS
Write-Host "Connecting to $vCenter" -ForegroundColor Blue
Connect-VIServer -Server $vCenter -User $vCenterUser -Password $vCenterPass -Force | Out-Null
Write-Host "Connected to $vCenter" -ForegroundColor Green

# Imports
Import-Module VMware.VimAutomation.Core
Import-Module VMware.PowerCLI

# Main
# Script to get the last Windows update info
$scriptContent = {
    $now = Get-Date
    $session = New-Object -ComObject "Microsoft.Update.Session"
    $searcher = $session.CreateUpdateSearcher()
    $historyCount = $searcher.GetTotalHistoryCount()
    $lastUpdate = $searcher.QueryHistory(0, 1) | Select-Object -ExpandProperty Date
    $daysSinceUpdate = ($now - $lastUpdate).Days
    return @{ LastUpdateDate = $lastUpdate; DaysSinceUpdate = $daysSinceUpdate }
}

# Get the list of VMs which are powered on
$vms = Get-VM | Where-Object { $_.PowerState -eq 'PoweredOn' }

# Get credentials for accessing the VMs
$guestCred = Get-Credential -UserName $vCenterUser -Message "Enter the password"

$notUpdatedVMs = @()

foreach ($vm in $vms) {
    $result = Invoke-VMScript -VM $vm -ScriptType PowerShell -ScriptText $scriptContent -GuestCredential $guestCred

    if ($result.DaysSinceUpdate -ge 90) {
        $notUpdatedVMs += "VM: $($vm.Name) - No - Last Update: $($result.LastUpdateDate) - Days Since Update: $($result.DaysSinceUpdate)"
    }
}

# Display the list of VMs not updated in the last 90 days
Write-Host "List of VMs not updated in the last 90 days:" -ForegroundColor Yellow
$notUpdatedVMs | ForEach-Object { Write-Host $_ }
0

There are 0 best solutions below