Powershell pro tip: how to more easily manage microsoft updates on windows 10

Pswindowsupdate

Media Creation Tool

Фирменная программа Microsoft, разработанная для создания установочных загрузочных флешек и установки актуальной версии Windows 10.

2. Согласитесь со всеми условиями эксплуатации продуктов Microsoft.

3. Запустите приложение и выберите вариант с обновлением текущего компьютера.

4. Дождитесь завершения процесса загрузки всех необходимых файлов.

5. Примите уведомления и условия лицензии.

6. Укажите, как поступать с личными файлами:

  • сохранить их и установленные на компьютере приложения, настройки;
  • сохранить только личные документы – файлы в каталоге с именем юзера останутся, программы придётся инсталлировать заново (их настройки никуда не денутся);
  • ничего не сохранить – на выходе получите чистую Windows 10.

7. Дождитесь пока закончится проверка и получение обновлений.

8. Запускайте установку.

8. Ждите.

9. После перезагрузки процесс продолжится.

10. В итоге появится загрузочный экран.

11. Как и во время инсталляции Виндовс 10, указываем удовлетворяющие параметры системы (действие требующееся при выборе «Ничего не сохранять»).

12. После краткого ознакомления с нововведениями запустится новый Рабочий стол.

Утилита Update Assistant помощник по обновлению Windows 10

Правильная установка Windows 10 на SSD диск

Сколько после установки весит windows 10 с разрядностью 64 и 32 bit?

Какие программы поставить после установки Windows 10?

Удаленное использование модуля с другого компьютера

Вам никто не мешает создать некий такой репозиторий модулей PowerShell на отдельной виртуальной машине и обращаться к ним удаленно. Установим для начала сессию с удаленным компьютером.

$session = New-PSSession -ComputerName w10-module

Удостоверимся, что на удаленном сервере есть нужные нам модули, через команду:

Get-Module -PSSession $session –ListAvailable

импортируем теперь в свою текущую сессию нужный модуль с удаленного сервера:

Import-Module -PSsession $session -Name VMware.PowerCLI

После завершите сеанс, когда закончите:

Remove-PSSession $session

Еще можно использовать командлет Invoke-Command. Тут вы подключаетесь к удаленному серверу и импортируете модуль.

$session = New-PSSession -ComputerName w10-module Invoke-Command {Import-Module VMware.PowerCLI} -Session $session

Сохраним на локальный компьютер нужный нам модуль.

Export-PSSession -Session $s -CommandName *-PowerCLI* -OutputModule RemSQLServer -AllowClobber

Данная команда создаст на вашем компьютер новый PowerShell модуль VMware.PowerCLI (в каталоге C:\Program Files\WindowsPowerShell\Modules ). Сами командлеты при этом не копируются. Далее закройте сессию.

Remove-PSSession $session

Теперь его можно локально импортировать и использовать.

Import the shared module

Now I need to import the shared module. This command makes sense, but is a bit stealth … that is, it is not really intuitive. Instead of simply supplying a module name, I include the complete path. I need to run the Windows PowerShell console with admin rights because the commands require admin rights to update my computer. Remember, modules are addressed by their folders that have the same name as the module itself; therefore, I simply type the path to the shared folder containing the module. The good thing is that tab expansion works and will fill out the path for me (to avoid misspelling of path names). The command is shown here.

ipmo \\dc1\Share\PSWindowsUpdate

Once I have imported the module, I use the Get-Command cmdlet to view the commands available to me. This is shown here.

PS C:\> gcm -Module pswindows*

CommandType     Name                                               ModuleName

———–     —-                                               ———-

Function        Add-WUOfflineSync                                  PSWindowsUpdate

Function        Get-WUHistory                                      PSWindowsUpdate

Function        Get-WUInstall                                      PSWindowsUpdate

Function        Get-WUInstallerStatus                              PSWindowsUpdate

Function        Get-WUList                                         PSWindowsUpdate

Function        Get-WURebootStatus                                 PSWindowsUpdate

Function        Get-WUServiceManager                               PSWindowsUpdate

Function        Get-WUUninstall                                    PSWindowsUpdate

Function        Remove-WUOfflineSync                               PSWindowsUpdate

Function        Test-ElevatedShell                                 PSWindowsUpdate

The command (advanced function) I want is called Get-WUInstall. There is complete comment-based Help, and the advanced function is extremely powerful. I recommend spending some time getting familiar with the options. By default, it connects to Windows Update, presents a listing of available updates, and prompts to accept. (There is an acceptall switch that will automatically accept the updates). On my computer, I ran the advanced function with defaults, and found a video driver I did not know existed. This is shown here.

PS C:\> Get-WUInstall 

Confirm

Are you sure you want to perform this action?

Performing operation “nVidia – Graphics Adapter WDDM1.1, Graphics Adapter WDDM1.2,

Other hardware – NVIDIA Quadro 2000M?” on Target “EDLT”.

Yes  Yes to All  No  No to All  Suspend  Help

(default is “Y”):y

X Status     KB          Size Title

– ——     —          —- —–

2 Accepted             226 MB nVidia – Graphics Adapter WDDM1.1, Graphics Adapter…

3 Downloaded           226 MB nVidia – Graphics Adapter WDDM1.1, Graphics Adapter…

4 Installed            226 MB nVidia – Graphics Adapter WDDM1.1, Graphics Adapter…

If I want to know if I need to reboot the computer, I use the Get-WURebootStatus function. This is shown here.

PS C:\> Get-WURebootStatus

Reboot is not Required.

If I need to perform a reboot on Windows 8 and Windows Server 2012, I can call the Restart-Computer cmdlet. But even on Windows 7 (or Windows XP, for that matter) running Windows PowerShell 2.0 and the Get-WUInstall advanced function, there are switches for reboot. For example, there is the AutoReboot switch as well as the IgnoreReboot switch.

Now I can configure my remote servers and use Windows Update to perform the updates. Cool. It think it will require a bit of scripting to be on the safe side, but the cool thing about Windows PowerShell is that if something does not exist by default, someone in the community generally steps up to the plate. Thanks to Michal Gajda for writing and for sharing a cool module.

Join me tomorrow when I will talk about more cool Windows PowerShell stuff.

Ed Wilson, Microsoft Scripting Guy

Doctor Scripto
Scripter, PowerShell, vbScript, BAT, CMD

Automate Windows Update with PowerShell

In order to orchestrate Windows Update with PowerShell, the module “PSWindowsUpdate” needs to be installed. This module contains cmdlets to manage the Windows Update Client (servers). This module is vital because it helps automate the deployment of Windows Update using the

  • “Invoke-WUInstall” command to install Windows Updates remotely on computers or with the following below that can be configured via task scheduler to automate updates on individual computers.
  • “Install-WindowsUpdate” for installing updates from Microsoft Update Center or with the – “Get-WindowsUpdate” to update Windows from WSUS.

More on PSWindowsUpdate

To make the Windows patch management process smooth and easy as discussed above, you can use the PSWindowsUpdate module. This module is publicly available and can be downloaded for free from the PowerShell Gallery. The main requirement is that a computer needs to run Windows OS versions starting from Vista or Windows Server 2008. Also, you need to have PowerShell 2.0 or later.

With PSWindowsUpdate, you can identify if any Windows updates are available for your computer. Moreover, this module allows you to centrally manage Windows updates across various Windows servers and workstations. This way, you can remotely control which updates are installed, removed, or hidden.

Note: This module is not installed by default on Windows Servers and when installed it contains a set of functions to check, download and install updates from PowerShell. First, download the PSWindowsUpdateModule:

Next, install the PSWindowsUpdateModule. To have the module installed in PowerShell 5 and above, use the cmdlets below. You may be interested in this guide as well.

Note: To automate this installation in an unattended (silent) mode, use the command by adding the “-Force” flag as shown below

To list all the modules installed, use the command below

Next, run the command below. If the updates are not already downloaded, the command will contact the WSUS and pull the updates, have the updates installed and restart the server.

Here is the meaning of the command.

Run Windows Update from Command Prompt (Command-line)

Windows Update can also be run through legacy CMD to get the latest updates. The only limitation running Windows Update through the command prompt is that it won’t show any progress. Only results are shown when the process is complete. Let’s see how to run it:

RestartDevice – Restart Windows after updates are installed

ScanInstallWait – Check for updates, download available updates and install them

  • Press the Windows key + R to open Run dialog.
  • Type cmd and then press Ctrl + Shift + Enter to open the command prompt in administrative mode.
  • Run the following command to check for new updates:wuauclt /detectnow 
  • Run the following command to install new updateswuauclt /updatenow

Since the command prompt does not show any progress, a better approach would be to check and install updates at the same time. Here’s the command for this:

wuauclt /detectnow /updatenow

The above-mentioned command will work in all versions of Windows, including Windows 7 and Windows Server 2008 R2. But if you are using Windows 10 or Windows Server 2016, you can use UsoClient command which has more options than wuauclt. You can run UsoClient with the following switches:

StartScan – Start checking for updates

StartDownload – Start downloading updates

StartInstall – Start installing downloaded updates

Обновление в режиме аудита (Windows Update PowerShell Module)

Для автоматического обновления системы из консоли вы можете взять на вооружение очень удобный модуль PowerShell, опубликованный в галерее TechNet. Он работает не только в режиме аудита, но именно в нем особенно ценен. Я протестировал модуль уже потом, когда готовил этот материал.

Конечно, с модулем надо немного разобраться, но я сильно сэкономлю вам время своими инструкциями. Тут ПКМ, в основном, извините уж

Сохраните архив PSWindowsUpdate.zip на USB-диск и (это важно!) щелкните на нем ПКМ – Свойства – Разблокировать файл.
Сохраните на USB-диске файл wu.cmd с одной командой:
PowerShell -ExecutionPolicy RemoteSigned -Command Import-Module PSWindowsUpdate; Get-WUInstall -AcceptAll -IgnoreReboot

В режиме аудита щелкните ПКМ на архиве – Распаковать все и выберите папку
Щелкните ПКМ на wu.cmd и выберите Запуск от имени администратора.

Это все! Доступные обновления загрузятся и установятся автоматически. Выглядит это примерно так:

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

Рекомендую повторить запуск wu.cmd на случай, если после установки первой партии обновлений появится вторая.

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

Get-WUInstall -ListOnly

В остальном же, модуль подробно задокументирован, поэтому я не буду разбирать все его параметры.

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

%SystemRoot%\system32\sysprep\sysprep.exe /generalize /oobe /shutdown /quiet

Это ведь было просто, не правда ли?

Модуль PSWindowsUpdate: управление обновлениями Windows из PowerShell

Для управления обновлениями Windows из командной строки очень удобно использовать специальный PowerShell модуль – PSWindowsUpdate. Модуль PSWindowsUpdate не встроен в Windows и является сторонним модулем, доступным в галерее скриптов Technet. PSWindowsUpdate позволяет администраторам удаленно проверять, устанавливать, удалять и скрывать определенные обновления на компьютерах и рабочих станциях. Модуль PSWindowsUpdate особо ценен при использовании для управления обновлениями в Core редакциях Windows Server, в которых отсутствуют графический интерфейс, а также при настройке образа Windows в режиме аудита.

Final notes

Once you apply the Auto-download updates, you can go back to your endpoint and run the following powershell command to ensure that your files were in fact downloaded. This will ensure that you are in fact receiving updates from WSUS

Get-WUInstall -MicrosoftUpdate -IgnoreUserInput -WhatIf -Verbose

You may also check if there’s any new updates available from the WSUS server:

Get-WUList -MicrosoftUpdate

and lastly, if you’re testing the module manually, you may trigger the updates yourself by running the following:

Install-WindowsUpdate -AcceptAll

As I mentioned there are other functions that you can take advantage of as well which are listed here

If you have any questions feel free to ask!

votes

Article Rating

Принудительная проверка Windows Update с помощью командного диалога Run

Я обнаружил, что самый простой способ принудительной проверки обновлений Windows — это использование команды в диалоге Run. Существуют и другие команды CMD и PowerShell, но давайте начнем с самого простого способа.

Откройте диалог Run (клавиша Windows + R) или откройте Поиск Windows и выполните следующую команду:

control update

Это вызовет графический пользовательский интерфейс Windows Update, который начнет проверку новых обновлений. Этот метод работает на всех версиях Windows, включая Windows 10 и Windows 11.

Есть другая команда, которая вызовет тот же эффект, но работает только в Windows 10 и Windows 11:

ms-settings:windowsupdate

Update Windows 10 from PowerShell

To check and install updates with PowerShell, use these steps:

  1. Open Start on Windows 10.

  2. Search for PowerShell, right-click the top result, and select the Run as administrator option.

  3. Type the following command to install the module to run Windows Update and press Enter:

    Install-Module PSWindowsUpdate

    Quick note: After installing the module, you no longer need to repeat step No. 3 to use the module and manage updates.

  4. Type A and press Enter to confirm.

  5. Type the following command to check for updates with PowerShell and press Enter:

    Get-WindowsUpdate
  6. Type the following command to install the available Windows 10 updates and press Enter:

    Install-WindowsUpdate
  7. Type A and press Enter to confirm.

Once you complete the steps, the latest cumulative updates will download and install on your computer.

Prevent specific updates from installing by hiding them

There may be times when you wish to exclude updates from the installation list. Microsoft has included several parameters that address these exceptions based on individual update names and IDs, KB articles, and categories of updates.

Similar to installing specific updates by KB article above, you can use the following command to prevent the installation of any updates that match the KB articles referenced:

Install-WindowsUpdate -NotKBArticle "KB1111111","etc" -AcceptAll 

Perhaps you prefer to not update specific applications, like Teams. The following command will install updates for all applications, except those that include “Teams” in the title:

Install-WindowsUpdate -NotTitle "Teams" -AcceptAll 

Lastly, if you wish to skip updates that fall under a particular category, for example, drivers or FeaturePacks, then the following command would block those updates while all others are installed:

Install-WindowsUpdate -NotCategory "Drivers","FeaturePacks" -AcceptAll 

Note: It is important to keep in mind that when creating the perfect scripting environment for your update methods, please include not only your preferences but take the time to test them individually and then again together as one all-encompassing script to ensure it all works properly.

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).

  1. Download the latest PSWindowsUpdate version from this page: https://gallery.technet.microsoft.com/scriptcenter/2d191bcd-3308-4edd-9de2-88dff796b0bc and unblock the downloaded file; Please note that only the old version of the module is available in the TechNet script gallery – v 1.5.6. While the NuGet package manager installs PSWindowsUpdate 2.1.1.2 from the PowershellGallery. Available PowerShell cmdlets and parameters may vary in different versions of the module.
  2. Extract the archive with the PS module into one of the following directories:  or % (the last one is better if you are going to use the module often);
  3. Allow scripts execution: 
  4. Import the module into your PowerShell session: 
    Note. In Windows 7/ Windows Server 2008 R2, when importing the PSWindowsUpdate module, the following error may appear: The term “Unblock-File” is not recognized as the name of a cmdlet. The cause is that the module uses some functions that appeared only in PowerShell 3.0. To use these functions, you will have either to update the PowerShell version or to delete the  line from the PSWindowsUpdate.psm1 file manually.

After installing the PSWindowsUpdate module on your computer, you can remotely install it on other computers or servers using the  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:

Доступ к WMI

Как мы знаем, Windows Management Instrumentation (WMI) — это реализация компанией Microsoft стандарта Common Information Model (CMI). В большинстве случаев WMI применяется ИT-специалистами для получения информации об аппаратном и программном обеспечении, установленном на данном компьютере. Как мы увидим в следующем примере, использование Windows PowerShell существенно облегчает доступ к информации, хранимой в WMI (рис. 17).

В первой строке мы применяем команду get-wmiobject
для получения информации о файле, используемом для свопинга памяти на диск и сохранения этой информации в переменной $pfu
:

PS C:\> $pfu = get-wmiobject – class ‘win32_pageFileUsage’

PS C:\> $pfu | get-member –membertype property | where_object { $_.name –nomatch ‘_’ }

Обычно для нахождения информации по определенному классу можно использовать команду get-member
без указания параметров, но в нашем примере нас интересуют только доступные свойства и только те из них, которые не содержат в имени символ подчеркивания. У внимательного читателя может возникнуть вопрос: каким образом мы узнали о существовании класса win32_pageFileUsage
? Ведь известно, что в WMI поддерживается более тысячи классов, помимо этого ряд приложений добавляет свои классы. Вы можете применить команду:

PS C:\> get-wmiobject –list

для получения списка всех существующих в системе классов. После того как мы определили доступные нам свойства класса, мы выводим содержимое интересующих нас свойств на экран:

PS C:\> $pfu.caption; $pfu.currentusage

Вторая часть нашего примера посвящена другому классу — win32_DiskDrive
, в котором хранится информация о дисках, установленных в системе. Этот класс — пример WMI-класса, содержащего более одного объекта. В нашем примере мы определяем значение свойства caption
первого диска, установленного в системе:

PS C:\> $dd.caption

Почему центр обновления не работает в режиме аудита Windows 8.1

Ответ поддержки Microsoft процитирован кем-то на форуме TechNet. Центр обновлений Windows проверяет, завершила ли система этап OOBE (из которого вы и входите в аудит). Если не завершила, обновление не выполняется.

С одной стороны, это предотвращает перезагрузку на этапе OOBE. С другой стороны, у ОЕМов появляется возможность контролировать набор устанавливаемых обновлений при создании фабричного образа, даже если он настроен на автоматическое обновление.

Почему Microsoft изменила поведение именно в Windows 8.1, я не знаю – возможно, именно по просьбам ОЕМов. Однако заметьте, что не работает именно обновление из панели управления, а значит есть обходной путь.

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). This is very convenient because the administrator doesn’t have to manually log on to remote Windows hosts to install updates. WinRM must be enabled and configured on remote computers (manually or via GPO).

Almost all PSWindowsUpdate module cmdlets allow you to manage and install Windows updates on remote computers with the attribute.

Install the PSWindowsUpdate module on remote computers and allow access via dynamic RPC ports to the dllhost.exe process in the Windows Defender Firewall. You can use the Invoke-Command cmdlet to configure the PSWindowsUpdate module on remote computers:

The PSWindowsUpdate module can be used to remotely manage Windows updates both on computers in an AD domain and in a workgroup (requires PowerShell Remoting configuration for workgroup environment).

In order to manage updates on remote computers, you need to add hostnames to your winrm trusted host list or configure PowerShell Remoting (WinRM) via HTTPS:

Or with PowerShell :

The following command will install all available updates on three remote Windows hosts:

The Invoke-WUJob cmdlet (previously called Invoke-WUInstall) will create a scheduler task on the remote computer that runs under a local SYSTEM account.

You can specify the exact time to install Windows updates:

You can check the status of the update installation task using the Get-WUJob:

If the command returns an empty list, then the update installation task on all computers has been completed.

Редактирование списка загрузки Windows

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

  • Во-первых, как по мне, 30 секунд — для кого-то много, для кого-то мало. Как может быть много? Ну, например, Вы включаете компьютер и идете ставить чайник, а по возвращению видите, что система, если и выбралась, то всё еще грузится. Так вот можно поменять это самое время на, в общем-то, любое значение от 1 до n. Возможно есть предел сего значения, но я не проверял, да и сильно сомневаюсь, что кому-то надо, чтобы система грузилась через 30 минут
  • Во-вторых, как я уже говорил выше, возможно, Вы (или Ваши знакомые) ставили второй\третий\пятый Windows (или другую операционную систему), но прервали установку или что-то не получилось в ходе неё, или Вы вовсе удалили одну из систем с жесткого диска. Только вот запись то об этой самой недопоставленной\удаленной Windows осталась и всячески надоедает, т.к. приходится всё время выбирать рабочую систему из списка. Так вот можно избавиться от лишних строк.
  • В-третьих. Многие любят всякие забавные примочки. В данном случае, можно, например, переименовать системы в списке как угодно, например, вместо Microsoft Windows XP поставить Mega Winda Vasi.
  • В-четвертых, допустим, Вам друг принес жесткий диск со своим Windows, но Вы не знаете как добавить операционную систему в список доступных, чтобы её можно было выбрать. Опять же это можно сделать там, где я сейчас расскажу.
  • В-пятых, есть несколько бредовая идея по использованию нижеописанного способа редактирования списка доступных для загрузок систем. Можно создать список из скажем 25 систем, но грузится из них будет одна, остальные в силу своего несуществования будут выдавать ошибку. Какая по счету работает будете знать только Вы, т.к Вы этот список и создадите, а злоумышленнику, включившему Ваш компьютер, придется раз 20 перезагружать компьютер в поисках рабочей системы. Кстати использовать это можно не только в целях безопасности, но и просто как розыгрыш друга, или подруги
Понравилась статья? Поделиться с друзьями:
Быть в курсе нового
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: