- Записки IT специалиста
- Используем PowerShell для автоматизации установки обновлений
- PSWindowsUpdate: Managing Windows Updates from PowerShell
- PSWindowsUpdate: Install Windows Update PowerShell Module
- Overview of PSWindowsUpdate Cmdlets
- PowerShell: List All Windows Updates Available for a Computer
- Install-WindowsUpdate: Installing Windows Updates with PowerShell
- Install Windows Update on Remote Computers with PowerShell
- Get-WUHistory: Viewing Windows Update History using PowerShell
- Remove-WindowsUpdate: Uninstalling Windows Updates
- Hide-WindowsUpdate: How to Hide Windows Updates with PowerShell?
- BootDev
- Страницы
- 2018-09-14
- PowerShell: Скачивание и установка обновлений Windows 10
- Содержание
- Проверка Наличия Обновлений
- Установка Доступных Обновлений
- Дополнительные Командлеты
- How to Use PowerShell to Manage Windows Updates
- How to install PSWindowsUpdate
- Commands in PSWindowsUpdate
- PSWindowsUpdate main parameters
- Filtering updates:
- Actions and targets:
- Client restart behavior:
- How to avoid accidental installs
- How to determine errors
- Flexible PowerShell management with Parallels RAS
Записки IT специалиста
Технический блог специалистов ООО»Интерфейс»
Используем PowerShell для автоматизации установки обновлений
Установка большого количества обновлений Windows Update обычно относится к тем рутинным операциям, которые каждый системный администратор хотел бы как можно сильнее автоматизировать. Действительно, данная задача занимает довольно много времени и требует время от времени отвлекаться, чтобы перейти от одного этапа к другому. Отчасти выручить в этой ситуации может создание собственного дистрибутива, уже включающего все необходимые обновления, но воспользоваться им удается не всегда. Иногда надо просто быстро обновить до актуального состояния какую-либо систему, тогда на помощь нам придет PowerShell.
Кроме того, в режиме аудита Windows 8 использовать Центр обновления Windows нельзя и установить обновления привычным образом не получится.
В этих, а также во многих других, случаях имеет смысл воспользоваться специальным модулем PowerShell для работы с Windows Update. Скачать его можно со страницы разработчика на Technet: Windows Update PowerShell Module. Мы настоятельно рекомендуем скачивать данный модуль именно оттуда.
Данный модуль работает в системах, начиная с Windows Vista и Server 2008 и требует PowerShell 2.0, хотя оптимально будет использование PowerShell 3.0 и выше.
Архив с модулем содержит папку PSWindowsUpdate, которую следует разместить в одном из двух возможных расположений:
Если вы хотите использовать данный модуль на постоянной основе, то имеет смысл разместить его в системной папке, в остальных случаях лучше использовать для этого директорию в профиле пользователя. Учтите, в папке Мои документы отсутствуют вложенные директории WindowsPowerShell и Modules, поэтому их следует создать самостоятельно.
Что дальше? В принципе уже сейчас можно воспользоваться одним из пакетных скриптов для данного модуля, доступных в сети. Но лучше сначала поработать с ним самостоятельно, после чего создать свой собственный пакетный файл.
Откроем консоль PowerShell от имени Администратора. Прежде всего выясним установленную политику командой:
По умолчанию обычно установлена политика Restricted, которая запрещает выполнение скриптов даже администратору. Поэтому изменим ее на RemoteSigned, позволяющую запускать локальные скрипты, также, в целях безопасности, рекомендуем изменять политику только для текущего сеанса. Выполним команду:
В 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, искать необходимую статью и скачивать пакет именно для вашей версии системы.
Для установки отдельного пакета используйте команду (номер пакета использован исключительно для примера):
Мы не ставили своей целью дать в данной статье полный обзор этого модуля, сфокусировавшись на решении конкретной задачи. Поэтому, если вас заинтересовали иные возможности данного модуля, то обратитесь к встроенной справке. Для этого откройте в блокноте файл интересующей функции, например, Get-WUInstall.ps1, каждый из которых автор снабдил подробным описанием.
Надеемся, что данный материал поможет вам автоматизировать некоторые рутинные задачи и добавит в ваш арсенал новый, удобный инструмент.
Помогла статья? Поддержи автора и новые статьи будут выходить чаще:
Или подпишись на наш Телеграм-канал:
PSWindowsUpdate: Managing Windows Updates from PowerShell
It is very convenient to use the special PSWindowsUpdate module for PowerShell to manage Windows updates from the command line interface. The PSWindowsUpdate is not integrated into Windows and is a third-party module available in Technet Script Gallery. PSWindowsUpdate allows administrators to remotely check, install, remove and hide updates on Windows servers and workstations. The PSWindowsUpdate module is especially valuable to manage updates on Windows Server Core, Hyper-V editions having no graphic interface, as well as when configuring a Windows image in the audit mode.
PSWindowsUpdate: Install Windows Update PowerShell Module
You can install the PSWindowsUpdate module on Windows 10 and Windows Server 2016 from the online repository (PSGallery) using the PackageManagement with a single command:
In my case, a warning appeared that PSWindowsUpdate 1.5.2.6 was already installed appeared. To install a newer module version, you need to run the command:
After the installation is complete, you need to check the package:
If you have an older Windows version (Windows 7/8.1/Windows Server 2008 R2/2012 R2) or you don’t have direct Internet access, you can install PSWindowsUpdate manually.
This module can be installed on any supported Windows versions starting from Vista / Windows Server 2008 with PowerShell 2.0 installed (though, PoSh 3.0 or newer is recommended).
After installing the PSWindowsUpdate module on your computer, you can remotely install it on other computers or servers using the Update-WUModule cmdlet. For example, to copy the PSWindowsUpdate module from your computer to two remote servers, run the commands (you need to access the remote servers via SMB protocol, TCP port 445):
To save (export) the PoSh module to a shared network folder for further importing of the module on other computers, run:
Overview of PSWindowsUpdate Cmdlets
You can display the list of available cmdlets in the PSWindowsUpdate module as follows:
Let’s describe the usage of the module commands in brief:
PowerShell: List All Windows Updates Available for a Computer
You can list the updates available for this computer on the update server using the Get-WindowsUpdate or Get-WUList commands.
To check the list of available updates on a remote computer, run this command:
Get-WUList –ComputerName server2
You can check where your Windows should get updates from. Run the following command:
As you can see, the computer is configured to receive updates from the local WSUS server (Windows Server Update Service = True). In this case, you should see a list of updates approved for your computer.
If you want to scan your computer on Microsoft Update servers in the Internet (in addition to Windows updates, these servers contain Office and other Microsoft product updates), run this command:
You will get this warning:
To allow scanning on Microsoft Update, run this command:
You can now scan to Microsoft Update. As you can see, in this case, additional updates were found for Microsoft Visual C ++ 2008 and Microsoft Silverlight.
To check the version of the Windows Update Agent on the computer, run the command:
To remove certain products or packages from the list of updates received by your computer, you can exclude them by:
For example, let’s exclude OneDrive, drivers and the specific KB from the list of updates:
Install-WindowsUpdate: Installing Windows Updates with PowerShell
To automatically download and install all available updates for your computer, run the command:
The AcceptAll key accepts installation of all update packages, and AutoReboot allows Windows to automatically restart after the updates are installed.
You can save the update installation history to the log file (you can use it instead of WindowsUpdate.log file).
You can install only the specific update packages by KB number:
In this case, you need to confirm the installation of each update manually.
If you want to exclude some updates from the installation list, run this command:
Install Windows Update on Remote Computers with PowerShell
The PSWindowsUpdate module allows you to install updates remotely on multiple workstations or servers at once (the PSWindowsUpdate must be installed/imported on these computers). It is very convenient since an administrator doesn’t have to log on manually to all servers when update installation is scheduled.
In order to manage updates on remote computers, you need to add host names to your winrm trusted host list:
Install the PSWindowsUpdate module on remote computers and allow to access the process dllhost.exe via dynamic RPC ports in the Windows Defender Firewall.
The following command will install all available updates on three remote servers:
In newer versions of the PSWindowsUpdate module, use the following command to remotely install updates on multiple computers:
You can install updates on a remote computer and send an email report to the administrator:
Get-WUHistory: Viewing Windows Update History using PowerShell
Using the Get-WUHistory cmdlet, you can get the list of updates installed on a computer earlier automatically or manually.
You can get the information about the date of installation of a specific update:
To find out if the update has been installed on multiple remote computers, you can use this PowerShell code:
Remove-WindowsUpdate: Uninstalling Windows Updates
To correctly uninstall the updates from PowerShell, you can use the Remove-WindowsUpdate cmdlet. Just specify the KB number as an argument of the KBArticleID parameter. To delay automatic computer restart, add the –NoRestart key:
Hide-WindowsUpdate: How to Hide Windows Updates with PowerShell?
Now the next time you scan for updates using the Get-WUInstall command, the hidden updates won’t be displayed in the list of updates available for installation.
This is how you can display the list of updates hidden on this computer:
Notice that the H (Hidden) attribute has appeared in the Status column of hidden updates.
To remove an update from hidden ones, run this command:
For those who feel uncomfortable in the PowerShell console, I would recommend a graphic Windows Update MiniTool to manage Windows 10 updates.
BootDev
Создание загрузочных дисков и прочие полезные мелочи
Страницы
2018-09-14
PowerShell: Скачивание и установка обновлений Windows 10
Начиная с версии Windows 10 1709, PowerShell обзавелся несколькими командлетами позволяющими выполнить установку обновлений.
Содержание
Проверка Наличия Обновлений
Выполняем проверку наличия новых обновлений.
Если выполнение команды завершилось выводом списка обновлений, то значит данные обновления в системе отсутствуют. В противном случае обновлений необходимых для установки нет.
Установка Доступных Обновлений
Установка ранне найденных обновлений выполняется командлетом Install-WUUpdates. Но простой запуск данного командлета ничего не даст. Так же как и подстановка UpdateID в качестве аргумента.
В качестве аргумента командлет Install-WUUpdates ожидает массив объектов типа Microsoft.Management.Infrastructure.CimInstance[], или же любой другой объект который можно привести к данному типу.
Получить подходящий объект можно из вывода командлета Start-WUScan.
Переменная $wu в данном случае будет содержать массив объектов CimInstance. Как раз то, что необходимо командлету Install-WUUpdates.
Учитывая все вышесказанное составим итоговую команду выполнения установки обновлений.
Данная команда запускает процесс получения списка обновлений в переменную $wu, и если список не пуст, то запускается командлет Install-WUUpdates с переданным списком ей списком $wu в качестве аргумента.
Запуск данной команды, при отсутствии доступных обновлений завершится соответствующим сообщением.
Выполнение процедуры по отдельности будет выглядеть следующим образом.
Дополнительные Командлеты
How to Use PowerShell to Manage Windows Updates
As is well known, keeping systems updated is essential to protecting enterprises from malicious attacks and security breaches that may compromise confidential information or even cause sensitive data losses.
Installing Windows update patches has always been a tedious, complex and long process. Although Microsoft eases these procedures through tools such as Windows Server Update Services (WSUS) or System Center Configuration Manager (SCCM), administrators still require command-line tools to automate the updates installation in certain scenarios.
How to install PSWindowsUpdate
PSWindowsUpdate is a third-party module that is not integrated into Windows by default. It can be downloaded from the PowerShell gallery, the most used repository for sharing PowerShell code. This module includes different cmdlets to manage the deployment of Windows updates from the command line.
Commands in PSWindowsUpdate
Installed aliases and cmdlets can be displayed typing Get-Command–module PSWindowsUpdate.
A brief description of principal commands is described below:
Get-WindowsUpdate: This is the main cmdlet of the module. It lists, downloads, installs or hides a list of updates meeting predefined requisites and sets the rules of the restarts when installing the updates.
Remove-WindowsUpdate: Uninstalls an update
Add-WUServiceManage: Registers a new Windows Update API Service Manager
Get-WUHistory: Shows a list of installed updates
Get-WUSettings: Gets Windows Update client settings
Get-WUInstallerStatus: Gets Windows Update Installer Status, whether it is busy or not
Enable-WURemoting: Enables firewall rules for PSWindowsUpdate remoting
Invoke-WUJob: Invokes PSWindowsUpdate actions remotely
PSWindowsUpdate main parameters
As shown in the previous section, the PSWindowsUpdate module includes different predefined aliases to ease patching processes. However, main parameters for the Get-WindowsUpdate cmdlet will be listed and explained below:
Filtering updates:
Actions and targets:
Client restart behavior:
How to avoid accidental installs
Windows updates and patches improve the features and stability of the system. However, some updates can mess up your system and cause instability, especially automatic updates for legacy software such as graphic card drivers. To avoid automatic updates and accidental installs for such applications, you can pause Windows updates.
Alternatively, you can hide the specific updates for those features you don’t want to get updated. When you hide the updates, Windows can no longer download and install such updates. Before you can hide the update, you need to find out its details, including its knowledge base (KB) number and title. Type the cmdlet below to list all the available updates on your system:
Get-WUList
To hide a specific update using the KB number, use your mouse to copy that KB number. Next, type the command below:
Highlight the “KB_Number” and click paste to replace that part with the actual KB number.
When prompted to confirm the action, type A, and hit the Enter key. If the command succeeds, the “Get-WUList” lists all the available updates, with hidden updates appearing with the symbol “H” under their status.
The KB number for the update may not be available for some updates. In this case, you can use the title to hide the update. To do this, list all the available updates via the cmdlet below:
Get-WUList
Next, use your mouse to copy the update title. Ensure it is distinct from other update titles. Now, type below command below to hide the update:
Don’t forget to paste the actual update title in the “Update Title” section.
When prompted to confirm the action, type A, and hit the Enter key. If the command succeeds, the “Get-WUList” lists all the available updates. However, the status of hidden updates appears with the symbol “H” underneath them.
How to determine errors
It is of crucial importance to have as much information as possible about Windows Updates installation processes in order to be able to fix erroneous deployments. The Get-WindowsUpdate cmdlet and the rest of cmdlets available in the module, provide a very detailed log level when managing updates, including status, KB ID, Size or Title.
Centralizing all of the computer logs and analyzing them searching for errors, administrators will always be able to know the patch level of their Windows computers and servers.
Flexible PowerShell management with Parallels RAS
In order to optimize new machines deployment time and management efforts, many administrators decide to build their RAS farms based on templates. When working with templates and cloning techniques, patching procedures are only made once in the master image. Deploying new machines based on the updated template will upgrade the environment within minutes.
Parallels® Remote Application Server (RAS) PowerShell SDK includes a complete set of tools to manage and configure RAS farms, including specific cmdlets to create templates from existing virtual machines or to deploy new machines based on those templates. Combining these commands with the PSWindowsUpdate PowerShell module, administrators will be able to automate the complete patching process of both their infrastructure servers and their templated-based machines.
Different RAS cmdlets that can be used to automate the updates installation processes, will be found in the following link: Parallels RAS PowerShell – VDI Example. The complete set of RAS commands is available here: RAS PowerShell Reference.
If you have any questions, please feel free to get in touch!