Update windows via powershell

Get Windows Update Status Information by Using PowerShell

January 20th, 2012

Summary: Learn how to use the WSUS Update Scope with Windows PowerShell to get update status information for client computers.

Microsoft Scripting Guy, Ed Wilson, is here. What a week. Boe Prox has certainly been sharing quite a bit of Windows PowerShell goodness. In case you have missed them, here are links to the blog series thus far. You can also see Boe’s biography in the Day 1 blog.

Today we are moving from working with the Computer Target Scope and generating some cool reports to working with the Update Scope on the WSUS server. Much like yesterday, I will dive into some of the objects that we have worked with throughout the week and make use of some of the methods that require the Update Scope object to work properly.

If you are asking, “What is the Update Scope?”

…As the name implies, this is a scope that can be used to filter a list of updates on the WSUS server.

Creating the Update Scope object

Much as we did with the Computer Target Scope object, we need first to create the Update Scope object so we can then look at its properties and make adjustments, if needed. To create this object, we need to use the Microsoft.UpdateServices.Administration.UpdateScope class. For more information about this class, see UpdateScope Class on MSDN. The code that follows creates an instance of the UpdateScope.

$updatescope = New-Object Microsoft.UpdateServices.Administration.UpdateScope

OK, let’s take a look at these properties. The image that follows displays this information.

Here is a list of the editable properties for the Update Scope object:

Gets or sets the approval states to search for. An update will be included only if it matches at least one of the specified states. This value may be a combination of any number of values from ApprovedStates. Defaults to Any.

Gets or sets the installation states to exclude. An update will be included only if it does not have any computers in any of the specified states. This value may be a combination of any number of values from UpdateInstallationStates. Defaults to 0.

Gets or sets whether to exclude optional updates from the list.

Gets or sets the minimum arrival date to search for. An update will be included only if its arrival date is greater than or equal to this value.

Gets or sets the minimum creation date to search for. An update will be included only if its creation date is greater than or equal to this value.

Gets or sets the installation states to search for. An update will be included only if it has at least one computer in one of the specified states. This value may be a combination of any number of values from UpdateInstallationStates.

Gets or sets whether or not to filter for WSUS infrastructure updates. If set to true, only WSUS infrastructure updates will be included. If set to false, all updates are included. Defaults to false.

Gets or sets the string to search for. An update will be included only if its Title, Description, Knowledge Base articles, or security bulletins contains this string.

Gets or sets the string to exclude. An update will be not be included if its Title, Description, Knowledge Base articles, or security bulletins contains this string.

Gets or sets the maximum arrival date to search for. An update will be included only if its arrival date is less than or equal to this value.

Gets or sets the maximum creation date to search for. An update will be included only if its creation date is less than or equal to this value.

Gets or sets the update approval actions to search for. An update will be included only if it is approved to at least one computer target group for one of the specified approval actions. This value may be a combination of any number of values from UpdateApprovalActions. Defaults to All.

Читайте также:  Windows 10 32 или 64 что лучше для слабого компьютера

Gets or sets the UpdateApprovalScope object that can be used to filter updates based on their approval properties.

Gets or sets the update sources to search for. An update will be included only if its update source is included in this value. This value may be a combination of any number of values from UpdateSources.

Gets or sets the update types to search for. An update will be included only if its update type is included in this value.

Yes, that is a fairly large list of properties that we can modify to suit our filtering needs. For the sake of simplicity, I am only going to update ApprovedStates, IncludedInstallationStates, and FromArrivalTime to show how you can see all of the updates that are needed by all of the clients since the last patch Tuesday. The code that follows updates these three properties.

Note: For the purposes of this blog, the last patch Tuesday was December 13. I set the ApprovedStates property to NotApproved because I only want to see updates that are required by the clients that are not already approved for installation. I set the IncludedInstallationStates to NotInstalled. This will tell the filter to look for only updates that are required by the clients, but have not been installed yet. This works fine for us because these updates are new to us and because we only want those for the most recent patch Tuesday.

First, I am going to show you the Administration Console and look at all updates that are required by the clients on the network since patch Tuesday. This is shown in the image that follows.

Note the number of updates (30) and some of the titles listed here. Although not all of the updates are listed in the image, I will show you a couple of methods that we can use to pull the exact same information by using Windows PowerShell!

This method, as you can probably tell, will allow us to view the number of updates that are returned by using the previously configured Update Scope.

Look at that, 30 updates—just as if it showed on the console.

I am going to expand on this slightly by using another method similar to one I showed you yesterday for the Computer Target Scope.

This will return a little more information about the updates, as you will see. Besides supplying the Update Scope object, I need to supply a Boolean value for whether to include DownStream Computers.

That is pretty cool, but we want to see those updates as well. Sure enough, we can use the GetUpdates() method and supply our Update Scope object to pull this information.

$wsus.GetUpdates($updatescope) | Select Title

And there you have it! You can compare the screenshots and you will see that the titles in the console match the titles from our query.

Now I will show you how to view the update approvals by using the Update Scope object and the GetUpdateApprovals() method. To make this work and to provide some useful information, I will make a couple of adjustments to the existing Update Scope. This revision is shown here.

Now we can use this scope in the method and pull some information. To do this, I use the GetUpdateApprovals method, and pass it the Update Scope. This technique is shown in the code that follows.

The result from the previous command is shown in the following image.

Let us clean this up a little so it is more readable and not just a bunch of GUIDs. The code that follows produces an easier to read output.

The result of the previous code is shown here.

The last two things I will show you in this blog are a couple of methods that require the Update Scope object and the Computer Target Scope object to work properly. They provide some nice reporting features similar to what you would see in the Administration Console.

Читайте также:  Драйвера для packard bell под windows

This method gets per-computer summaries for each of the specified computers, summed across all of the specified updates.

Let’s see this in action, where I use the following code to gather this information.

$computerscope = New-Object Microsoft.UpdateServices.Administration.ComputerTargetScope

$updatescope = New-Object Microsoft.UpdateServices.Administration.UpdateScope

The output from the previous code produces a nice table, as shown here.

Let’s see how this compares to what you would see in the console. One thing you do not have available in the console is the DownloadedCount, which our previous code nicely displayed.

Lastly, let’s look at the GetSummariesPerUpdate() method to get per-update summaries for each of the specified updates, summed across all of the specified computers. The following code uses this method.

Note: I changed the Update Scope to what I had at the beginning of this blog. This is so I can more accurately compare the output here with what is in the Administration Console.

The output from the previous code is shown here.

Now compare the previous image, with the console (shown here), and you will see that they match up as planned.

So there you have it. We spent the week starting out with a WSUS server installation, then doing some basic administration, and we finished by providing some reports using Windows PowerShell—and we haven’t even begun to scratch the surface of what we can do. But working with WSUS doesn’t end here! This weekend I will talk about update 2.0 to my WSUS module, PoshWSUS, which you can use to more easily manage and maintain a WSUS server.

Boe, this is great stuff. Thank you for sharing with us. WSUS Week will continue tomorrow.

Scan, download and install Windows Updates with PowerShell

  • Refresh membership in AD security groups without reboot or logoff — Thu, Apr 15 2021
  • Create a cluster name object and solve cluster connection problems — Thu, Apr 1 2021
  • Install updates for server clusters using Windows Admin Center — Thu, Mar 25 2021

While most Windows features have long supported detailed automation via PowerShell, this option was missing for the update client; it is now available to a limited extent. Compared to the popular PSWindowsUpdate by Michal Gajda, Microsoft’s own module is less powerful.

Availability as an advantage ^

The main advantages of Windows Update Provider are its official support by Microsoft and that all newer versions of the operating system already have it on board. Therefore, when using it for remote management, you can assume that the required functions are already available on the target computer. In contrast, third-party modules must first be installed on every managed PC.

However, it is not possible to copy Microsoft’s Windows Update Provider to older versions of Windows, such as Server 2012 R2 or 2016, because the CIM class required by the functions does not exist on those versions.

More control over updates ^

Command line tools such as usoclient.exe, wuinstall, or PowerShell cmdlets give admins more control over the update process because they can explicitly request the scan, download, install, or restart. This is useful, for example, if you want to secure a freshly installed computer by installing the latest patches. In addition, PowerShell is useful on Server Core because there is no GUI for managing updates.

Overview of the range of functions ^

If you search for Windows Update modules using

Записки IT специалиста

Технический блог специалистов ООО»Интерфейс»

  • Главная
  • Используем PowerShell для автоматизации установки обновлений

Используем PowerShell для автоматизации установки обновлений

Установка большого количества обновлений Windows Update обычно относится к тем рутинным операциям, которые каждый системный администратор хотел бы как можно сильнее автоматизировать. Действительно, данная задача занимает довольно много времени и требует время от времени отвлекаться, чтобы перейти от одного этапа к другому. Отчасти выручить в этой ситуации может создание собственного дистрибутива, уже включающего все необходимые обновления, но воспользоваться им удается не всегда. Иногда надо просто быстро обновить до актуального состояния какую-либо систему, тогда на помощь нам придет PowerShell.

Кроме того, в режиме аудита Windows 8 использовать Центр обновления Windows нельзя и установить обновления привычным образом не получится.

В этих, а также во многих других, случаях имеет смысл воспользоваться специальным модулем PowerShell для работы с Windows Update. Скачать его можно со страницы разработчика на Technet: Windows Update PowerShell Module. Мы настоятельно рекомендуем скачивать данный модуль именно оттуда.

Читайте также:  Как проверить платформу windows

Данный модуль работает в системах, начиная с Windows Vista и Server 2008 и требует PowerShell 2.0, хотя оптимально будет использование PowerShell 3.0 и выше.

Архив с модулем содержит папку PSWindowsUpdate, которую следует разместить в одном из двух возможных расположений:

Если вы хотите использовать данный модуль на постоянной основе, то имеет смысл разместить его в системной папке, в остальных случаях лучше использовать для этого директорию в профиле пользователя. Учтите, в папке Мои документы отсутствуют вложенные директории WindowsPowerShell и Modules, поэтому их следует создать самостоятельно.

Что дальше? В принципе уже сейчас можно воспользоваться одним из пакетных скриптов для данного модуля, доступных в сети. Но лучше сначала поработать с ним самостоятельно, после чего создать свой собственный пакетный файл.

Откроем консоль PowerShell от имени Администратора. Прежде всего выясним установленную политику командой:

По умолчанию обычно установлена политика Restricted, которая запрещает выполнение скриптов даже администратору. Поэтому изменим ее на RemoteSigned, позволяющую запускать локальные скрипты, также, в целях безопасности, рекомендуем изменять политику только для текущего сеанса. Выполним команду:

Ключ -Scope позволяет задавать область применения политики, в данном случае это текущий процесс. Теперь можно выполнить импорт модуля командой:

В Windows 7 и иных системах, использующих PowerShell 2.0 вы можете столкнуться со следующей ошибкой: Имя «Unblock-File» не распознано как имя командлета. Она возникает из-за использования в одном из скриптов функции появившейся в PowerShell 3.0.

Однако ее несложно исправить. В папке с модулем откройте файл PSWindowsUpdate.psm1 и удалите в первой строке последовательность:

Сохраните исправленный файл и повторите импорт модуля. Теперь можно приступить к работе с ним.

Прежде всего получим список доступных обновлений:

А вот и первый сюрприз, в списке обновлений присутствуют языковые модули, Skype и обновление для перехода на Windows 10. Все это приехало бы на ваш компьютер, воспользуйся вы одним из популярных скриптов для этого модуля, доступных в сети.

К счастью модуль обладает широкими возможностями. Мы можем исключить пакеты из списка по их категории, ключ -NotCategory, названию, ключ -NotTitle, или номеру обновления, ключ -NotKBArticleID. Используем каждый из них, в нашем случае уберем категорию языковых пакетов, Skype и обновление до Windows 10:

Вот, уже гораздо лучше.

Теперь можно установить обновления командой:

Ключи -AcceptAll и -IgnoreReboot включают одобрение всех пакетов и подавляют требование перезагрузки после установки некоторых обновлений.

Убедившись, что все работает как надо, можно создать собственный пакетный файл, откроем блокнот и в одну строку запишем:

Данная команда запускает PowerShell, устанавливает политику RemoteSigned, импортирует модуль, затем передает ему вышеуказанную команду. В общем делает все тоже самое, что мы только-что выполнили вручную. Сохраните данный файл как PSWindowsUpdate.cmd и теперь все что вам потребуется, это разместить модуль в нужном расположении и запустить данный пакетный файл с правами администратора.

Удобно? Да. Правда учтите, что некоторые обновления требуют обязательной установки предыдущих, поэтому, если вы давно не обновлялись, данный скрипт придется запускать несколько раз. Но это все равно проще, чем проделывать все эти операции вручную, кликнул на скрипт и занимайся своими делами, время от времени поглядывая на экран.

В Windows 8 языковые пакеты через WindowsUpdate не распространяются, поэтому команду можно немного упростить.

Однако на этом возможности данного модуля не заканчиваются, он позволяет быстро установить нужные обновления зная только их номер. Это значительно облегчает задачу, так как не надо посещать сайт Microsoft, искать необходимую статью и скачивать пакет именно для вашей версии системы.

Для установки отдельного пакета используйте команду (номер пакета использован исключительно для примера):

Если надо установить несколько пакетов, то разделите их номера запятыми и добавьте ключ -IgnoreReboot, например:

Мы не ставили своей целью дать в данной статье полный обзор этого модуля, сфокусировавшись на решении конкретной задачи. Поэтому, если вас заинтересовали иные возможности данного модуля, то обратитесь к встроенной справке. Для этого откройте в блокноте файл интересующей функции, например, Get-WUInstall.ps1, каждый из которых автор снабдил подробным описанием.

Надеемся, что данный материал поможет вам автоматизировать некоторые рутинные задачи и добавит в ваш арсенал новый, удобный инструмент.

Помогла статья? Поддержи автора и новые статьи будут выходить чаще:

Или подпишись на наш Телеграм-канал:

Оцените статью