2014-09-26 4 views
3

В настоящее время я пишу тип автоматизированной программы, которая, среди прочего, ищет обновления для Windows. Он может искать и получать обновления просто отлично, но у меня возникают проблемы с сверлением, для какого приоритета есть обновление. Я хотел бы иметь результат, похожий на:Как узнать, является ли Windows Update необязательным, рекомендуемым или важным

Всего обновления: 25 Важно: 12 дополнительно: 13

.IsMandatory поле используется только, когда обновление специально для самой АВП, так важные обновления не обязательно помечены значком .IsMandatory.

Фрагмент кода для поиска АВП ниже:

Dim updateSession ' Object to hold our MS Update Session 
Dim updateSearcher ' Object to perform our MS Win Update Search 
Dim results  ' Object to hold our MS Win Update Search Results 
Dim stopWatch As New Stopwatch() 
stopWatch.Start() 

outputWriter.WriteLine("----WINDOWS [email protected] " & Now, False) 
outputWriter.WriteLine(" -We are beginning our update search. Please note, this may take a few minutes." & _ 
         " On Windows Server 2003 this may take 800 years.", False) 

' We cannot guarantee the update check will succeed, so use a try catch in case of error. 
Try 
    updateSession = CreateObject("Microsoft.Update.Session") 
    updateSearcher = updateSession.CreateUpdateSearcher() 
    results = updateSearcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0") 
Catch ex As Exception 
    outputWriter.WriteLine(" ERROR: Something went wrong in our update search. Details below...", False) 
    outputWriter.WriteLine(" Error Msg: " & ex.Message, False) 
    Return 1 
End Try 

Dim imp_updates = 0 
Dim opt_updates = 0 
For i = 0 To results.Updates.Count - 1 
    Dim update = results.Updates.Item(i) 
    If update.IsMandatory = False Then 
     opt_updates = opt_updates + 1 
    Else 
     imp_updates = imp_updates + 1 
    End If 
Next 

outputWriter.WriteLine("Important Updates: " & imp_updates, True) 
outputWriter.WriteLine("Optional Updates: " & opt_updates, True) 

ответ

0

Вы должны быть в состоянии проверить MsrcSeverity в обновлении:

Select Case update.MsrcSeverity 
     Case "Important" 
     Case "Critical" 
     Case "Moderate" 
     Case "Low" 
     Case "Unspecified" 
    End Select 
+0

Я только что попробовал, но он показывает 2 важных обновления, которые у меня есть как «неуказанные». Возможно, он там для использования, и MS не использует его очень эффективно, ха-ха. Я сделал поиск в Интернете о MsrcSeverity и, по-видимому, он используется только тогда, когда обновление связано с исправлением безопасности. Такой патч для дыры в безопасности, и патч оценивается с серьезным защитным отверстием, которое он фиксирует. – WoofDg79

1

Оказывается, что у меня не было ссылки на WUApi.DLL в моем коде. Как только я включил эту ссылку, я смог успешно выполнить мой результат как IUpdate3. IUpdate3 - это интерфейс, который содержит свойство BrowseOnly. Что такое BrowseOnly, указывает, является ли обновление необязательным или нет. Используя BrowseOnly, я могу определить, важно или необязательно обновление.

Ниже (IUpdate3 используется примерно в середине кода фрагмента) ...

''' <summary> 
''' Performs a windows update check for any updates that are... 
''' A: Not installed 
''' B: Not hidden 
''' C: Software updates (OS and software, no hardware updates) 
''' </summary> 
''' <returns>0 on success, 1 on failure</returns> 
''' <remarks></remarks> 
Function checkForUpdates() As Integer 

    Dim updateSession ' Object to hold our MS Update Session 
    Dim updateSearcher ' Object to perform our MS Win Update Search 
    Dim results  ' Object to hold our MS Win Update Search Results 
    Dim stopWatch As New Stopwatch() 
    stopWatch.Start() 

    outputWriter.WriteLine("----WINDOWS [email protected] " & Now, False) 
    outputWriter.WriteLine(" -We are beginning our update search. Please note, this may take a few minutes." & _ 
          " On Windows Server 2003 this may take 800 years.", False) 

    ' We cannot guarantee the update check will succeed, so use a try catch in case of error. 
    Try 
     updateSession = CreateObject("Microsoft.Update.Session") 
     updateSearcher = updateSession.CreateUpdateSearcher() 
     results = updateSearcher.Search("IsInstalled=0 and Type='Software' and IsHidden=0") 
    Catch ex As Exception 
     outputWriter.WriteLine(" ERROR: Something went wrong in our update search. Details below...", False) 
     outputWriter.WriteLine(" Error Msg: " & ex.Message, False) 
     Return 1 
    End Try 

    outputWriter.WriteLine(" -Windows update search has successfully completed. Beginning iteration of result set...", False) 

    ' Similar to above, we cannot guarantee iterating through our result set will succeed. Use a try catch. 
    Try 
     Dim totalUpdates = results.Updates.Count 
     outputWriter.WriteLine("-----Windows [email protected] " & Now, True) 
     If results.Updates.Count = 0 Then 
      outputWriter.WriteLine("Total Updates: 0", True) 
      outputWriter.WriteLine("Important:  0", True) 
      outputWriter.WriteLine("Optional:  0", True) 
     Else 
      Dim imp_updates = 0 
      Dim opt_updates = 0 
      For i = 0 To totalUpdates - 1 
       Dim update = results.Updates.Item(i) 
       If CType(update, WUApiLib.IUpdate3).BrowseOnly = True Then ' BrowseOnly is specifically used for whether an update is deemed optional or not (True for optional) 
        opt_updates = opt_updates + 1 
       Else 
        imp_updates = imp_updates + 1 
       End If 
      Next 

      outputWriter.WriteLine("Total Updates: " & totalUpdates, True) 
      outputWriter.WriteLine("Important:  " & imp_updates, True) 
      outputWriter.WriteLine("Optional :  " & opt_updates, True) 

     End If 
     stopWatch.Stop() 
     If stopWatch.ElapsedMilliseconds >= 1000 Then 
      outputWriter.WriteLine("--------Total Time: " & Math.Round((CDbl(stopWatch.ElapsedMilliseconds)/1000), 2) & " Sec----------------" & vbCrLf, True) 
     Else 
      outputWriter.WriteLine("--------Total Time: " & stopWatch.ElapsedMilliseconds & " MS-------------------" & vbCrLf, True) 
     End If 

    Catch ex As Exception 
     outputWriter.WriteLine(" ERROR: We encountered an issue while iterating through Windows Update Search Results. Details below...", False) 
     outputWriter.WriteLine(" Error Msg: " & ex.Message, False) 
     Return 1 
    End Try 

    outputWriter.WriteLine(" -Iteration of Windows Update Search Results has successfully completed.", False) 
    outputWriter.WriteLine("-------------------------" & vbCrLf, False) 

    ' Clean up our objects. 
    updateSession = Nothing 
    updateSearcher = Nothing 
    results = Nothing 

    ' Success! 
    Return 0 
End Function 
0

Цикл по results.Updates.Count, а затем проверить для каждого Update.Item его названия Категории элементов.

For i As Integer = 0 To results.Updates.Count - 1 
    updateCategories = results.Updates.Item(i).Categories 
    For j As Integer = 0 To updateCategories.Count - 1 
     updateCategorie = updateCategories.Item(j).Name 
     Select Case updateCategorie 
      Case "Updates" 
       'do something 
      Case "Critical Updates" 
       'do something 
      Case "Security Updates" 
       'do something 
      Case "Service Packs" 
       'do something 
      Case "Update Rollups" 
       'do something 
      Case "Feature Packs" 
       'do something 
      Case Else 
       'do something 
     End Select 
    Next 
Next