Как загрузить классы в модуле power shell глобально

In this guide, we will introduce the PowerShell Active Directory Module, exploring what it is, its role in simplifying management tasks, and how to install and import it efficiently.

При попытке запустить командлет из установленного на компьютере модуля PowerShell может появится ошибка:

The command XXX was found in the module, but the module YYY could not be loaded.

В моем случае эта ошибка появилась при попытке подключиться к тенанту Microsoft 365 с помощью модуля Exchange Online PowerShell.

Connect-ExchangeOnline : The 'Connect-ExchangeOnline' command was found in the module 'ExchangeOnlineManagement', but the module could not be loaded. For more information, run 'Import-Module ExchangeOnlineManagement'. + CategoryInfo : ObjectNotFound: (Connect-ExchangeOnline:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CouldNotAutoloadMatchingModule

Ошибка при загрузке команды из PowerShell модуля в сессию

Чаще всего эта ошибка означает, что у вас на компьютере запуск сторонних модулей ограничивается настройками PowerShell Execution Policy.

В данном случае политика Restricted запрещает запуск сторонних скриптов.

Get-ExecutionPolicy

Попробуйте загрузить модуль командой:

Должна появится ошибка:

Import-Module: File C:\Program Files\WindowsPowerShell\Modules\ExchangeOnlineManagement\3.3.0\netFramework\ExchangeOnlineManagement.psm1 cannot be loaded because running scripts is disabled on this system.

Запуск PowerShell скриптов ограничен на этом компьютере

Можно разрешить запускать команды из внешних PowerShell модулей только в текущей сессии:

Set-ExecutionPolicy RemoteSigned -scope Process

Или можно запустить запуск любых локальных скриптов для текущего пользователя:

Если при попытке импортировать модуль появится ошибка вида:

Import-Module : Could not load file or assemblyor one of its dependencies. The system cannot find the file specified.

В этом случае скорее всего модуль загружен не полностью или поврежден. Удалите каталог с модулем с диска и переустановите модуль. PowerShell модули устаналиваются в одну из следующих директорий:

  • C:\Users\YourUserName\Documents\WindowsPowerShell\Modules
    – в профиле текущего пользователя
  • C:\Program Files\WindowsPowerShell\Modules
    – обычно сюда устаналиваются сторониие модулиЮ доступные для всех пользователей
  • C:\Windows\system32\WindowsPowerShell\v1.0\Modules
    – встроенные в Windows модули

Еще один вариант ошибки импорта модуля:

import-module : File …\…\modulename.psm1 cannot be loaded. The file …\…\modulename.psm1 is not digitally signed. You cannot run this script on the current system

Кроме исправления настроек политики запуска PowerShell скриптов причина такой ошибки может быть в том, что указанный файл модуля был вручную скачан с Интернета. В этом случае нужно просто разблокировать скачанный файл командой:

  • Define your classes as part of your script’s root module (*.psm1, referenced via the RootModule module-manifest entry) instead of your current approach of using a *.ps1 file that is loaded into the caller’s scope via the ScriptsToProcess manifest entry.

    • In other words: you then won’t need a ScriptsToProcess entry (at least not for exporting your classes and enums).
    • The linked documentation notes (emphasis added):

    • Only the importer and its descendent scopes see the imported module’s classes (and enums).

    • Because using module is a parse-time statement, the target module path must not contain variables, but modules discoverable via $env:PSModulePath can be referenced by name only (e.g. using module MyModule); relative paths are resolved against the caller’s own file-system location (rather than against the current directory).

    • Once a module is imported with using module in a given session, it cannot be forcefully re-imported; that is, if you want to modify your class and/or enum definitions, you’ll need to start a new session to see the changes.

  • However, the Exporting classes with type accelerators section of the about_Classes help topic describes a workaround that makes classes of your choice available session-globally, in all scopes and runspaces, and also works with module auto-loading and Import-Module

    • As with the using module-based approach, you won’t be able to reload modified class definitions in a given session – start a new session instead.

    • Unlike with the using module-based approach (which you may still choose to combine with the suggested approach), the (possibly implicit) importer must not rely on the classes to be available at parse time, i.e. must not try to reference them via type literals in class definition of its own – see this answer for details.

      • While the type-accelerator approach technically allows you to place the class and enum definitions in a nested module or a *.ps1 file dot-sourced from your root module, this is best avoided if you want your module to also support the using module importing technique for parse-time availability of the classes.
    • The linked help topic also includes event-based code for attempting to remove exported class definitions when the module is unloaded (Remove-Module), however, this does not work (as of PowerShell 7.4.1), and has therefore been omitted in the code below.

:/>  Удалить обновление при помощи DISM.

Note that with either approach above, classes and enums won’t be available until after your module has been imported into a given session.
That is, unlike functions and cmdlets in auto-loading modules, they aren’t discoverable prior to import.

Example *.psm1 root-module content:

# Since the quasi-exported class will be available *process-wide*
# and therefore also in *other runspaces*, be sure to define it with
# the [NoRunspaceAffinity()] attribute.
# Caveat: **v7.4+ only**
[NoRunspaceAffinity()]
class SomeClass { # Note: 'SomeClass' is both its .Name and .FullName. [int] Get() { return 42 }
}
# Define the types to export with type accelerators.
# Note: Unlike the `using module` approach, this approach allows
# you to *selectively* export `class`es and `enum`s.
$exportableTypes = @( [SomeClass]
)
# Get the non-public TypeAccelerators class for defining new accelerators.
$typeAcceleratorsClass = [psobject].Assembly.GetType('System.Management.Automation.TypeAccelerators')
# Add type accelerators for every exportable type.
$existingTypeAccelerators = $typeAcceleratorsClass::Get
foreach ($type in $exportableTypes) { # !! $TypeAcceleratorsClass::Add() quietly ignores attempts to redefine existing # !! accelerators with different target types, so we check explicitly. $existing = $existingTypeAccelerators[$type.FullName] if ($null -ne $existing -and $existing -ne $type) { throw "Unable to register type accelerator [$($type.FullName)], because it is already defined with a different type ([$existing])." } $typeAcceleratorsClass::Add($type.FullName, $type)
}

Installing, importing, and loading modules

In PowerShell, understanding the distinction between installing, importing, and loading modules is crucial. 

  • Install-Module: This command is used to download and install a module from an online repository like the PowerShell Gallery. It’s typically used when you want to add a new module to your system.
  • Import-Module: Once a module is installed, the Import-Module cmdlet is used to make its cmdlets available for use in the current PowerShell session. This is necessary to execute the cmdlets and leverage the functionality of the module.
  • Load-Module: The Load-Module cmdlet is used to load a module into the current session’s memory, making its cmdlets available for use without importing. This approach is beneficial when you want to keep the module in memory for an extended period or when dealing with large modules to minimize loading times.

Удаление обновлений в Windows с помощью PowerShell

Для корректного удаления обновления Windows используется командлет Remove-WindowsUpdate. Вам достаточно указать номер KB в качестве аргумента параметра KBArticleID.

Remove-WindowsUpdate -KBArticleID KB4011634

Install Active Directory PowerShell Module

  • Operating system: Windows Server is recommended for server installations, while Windows 10 or Windows 11 are suitable for client installations.
  • PowerShell version: Ensure that you have PowerShell 5.1 or later installed on your system.
  • Remote Server Administration Tools (RSAT): Depending on your Windows version, you may need to install RSAT, which includes the Active Directory module.
  • Internet access: Ensure that your system has internet access to download the module from the PowerShell Gallery. If your system is behind a proxy, you may need to configure proxy settings for PowerShell.

The steps required to install the Active Directory PowerShell Module vary slightly depending on your Windows operating system version, with additional pop-ups and confirmation dialogues present in some versions. 

:/>  Лефт шифт на клавиатуре

These are the core steps:

  1. Open PowerShell as administrator
  2. Use Install-Module cmdlet:
  3. Confirm installation: Once the installation is complete, you may need to confirm that you want to install the module by typing ‘Y’ and pressing Enter.
  4. Check the execution policy

Import Active Directory PowerShell Module

Once the module is installed, it needs to be imported into your PowerShell session before you can start using its cmdlets. Importing loads the module into memory, making its functionality available for execution:

  1. Open PowerShell:
  2. Use Import-Module cmdlet
  3. Verify import: You can verify that the module has been successfully imported by running this simple cmdlet: Get-Command -Module RSAT-AD-PowerShell

Loading the module efficiently

To ensure that the Active Directory module is loaded automatically when you open a PowerShell session, you can add the import command to your PowerShell profile script. This script runs every time you open a new PowerShell session:

  1. Check if a profile exists:

If the command returns False, you need to create a profile (step 2). If it returns True, proceed to step 3.

  1. Create a profile (if needed):
  2. Edit the profile script:
  3. Add Import-Module line:

>Просмотр истории установленных обновлений в Windows

С помощью команды Get-WUHistory вы можете получить список обновлений, установленных на компьютере ранее автоматически или вручную.

Get-WUHistory - история установки обновлений

Можно получить информацию о дате установки конкретного обновления:

Get-WUHistory найти установленные обновления

Вывести даты последнего сканирования и установки обновлении на компьютере:

Get-WULastResults время последней установки обновлений в Windows

What is the PowerShell Active Directory Module?

Simplifying Active Directory management

This automation not only reduces the likelihood of human error but also significantly speeds up the execution of repetitive tasks, as well as freeing up time for other duties.

Скрыть ненужные обновления Windows с помощью PowerShell

Вы можете скрыть определенные обновления, чтобы они никогда не устанавливались службой обновлений Windows Update на вашем компьютер (чаще всего скрывают обновления драйверов). Например, чтобы скрыть обновления KB2538243 и KB4524570, выполните такие команды:

$HideList = "KB2538243", "KB4524570"
Get-WindowsUpdate -KBArticleID $HideList -Hide

или используйте alias:

Hide-WindowsUpdate -KBArticleID $HideList -Verbose

Hide-WindowsUpdate - скрыть обновление, запретить установку

Теперь при следующем сканировании обновлений с помощью команды Get-WindowsUpdate скрытые обновления не будут отображаться в списке доступных для установки.

Вывести список скрытых обновлений:

Обратите внимание, что в колонке Status у скрытых обновлений появился атрибут H (Hidden).

Get-WindowsUpdate –IsHidden отобразить скрытые обновления windows

Отменить скрытие обновлений можно так:

Get-WindowsUpdate -KBArticleID $HideList -WithHidden -Hide:$false

Show-WindowsUpdate -KBArticleID $HideList

Установка обновлений Windows с помощью команды Install-WindowsUpdate

Install-WindowsUpdate -MicrosoftUpdate -AcceptAll -AutoReboot

Ключ AcceptAll включает одобрение установки для всех пакетов, а AutoReboot разрешает автоматическую перезагрузку Windows после завершения установки обновлений.

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

  • IgnoreReboot – запретить автоматическую перезагрузку;
  • ScheduleReboot – задать точное время перезагрузки компьютера.

Можете сохранить историю установки обновлений в лог файл (можно использовать вместо WindowsUpdate.log).

Можно установить только конкретные обновления по номерам KB:

Get-WindowsUpdate -KBArticleID KB2267602, KB4533002 -Install

Install-WindowsUpdate установка обновлений windows с помощью powershell

Если вы хотите пропустить некоторые обновления при установке, выполните:

Install-WindowsUpdate -NotCategory "Drivers" -NotTitle OneDrive -NotKBArticleID KB4011670 -AcceptAll -IgnoreReboot

Проверить, нужна ли перезагрузка компьютеру после установки обновления (атрибуты RebootRequired и RebootScheduled):

Get-WURebootStatus нужна ли перезагрузка Windows после установки обновлений

Установка модуля управления обновлениями PSWindowsUpdate

В современных версиях Windows 10/11 и Windows Server 2022/2019/2016 модуль PSWindowsUpdate можно установить из онлайн репозитория PowerShell Gallery с помощью команды:

Install-Module -Name PSWindowsUpdate

Подтвердите добавление репозитариев, нажав Y. Проверьте, что модуль управлениям обновлениями установлен в Windows:

Get-Package -Name PSWindowsUpdate

Установить powershell модуль PSWindowsUpdate

Можно удаленно установить PSWindowsUpdate на другие компьютеры в сети. Следующая команда скопирует файлы модуля на указанные компьютеры (для доступа к удаленным компьютерам используется WinRM).

$Targets = "srv1.winitpro.loc", "srv2.winitpro.loc"
Update-WUModule -ComputerName $Targets -local

Политика выполнения PowerShell скриптов в Windows по умолчанию блокирует запуск командлетов из сторонних модулей, в том числе PSWindowsUpdate. Чтобы разрешить запуск любых локальных скриптов, выполните команду:

:/>  Как определить версию wsl в Windows 11, 10 and 7?

Set-ExecutionPolicy –ExecutionPolicy RemoteSigned -force

Либо вы можете разрешить запускать команды модуля в текущей сессии PowerShell:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process

Импортируйте модуль в сессию PowerShell:

Выведите список доступных командлетов:

Get-command -module PSWindowsUpdate

список командлетов модуля pswindowupdate

Проверить текущие настройки клиента Windows Update:

ComputerName : WKS22122
WUServer : http://MS-WSUS:8530
WUStatusServer : http://MS-WSUS:8530
AcceptTrustedPublisherCerts : 1
ElevateNonAdmins : 1
DoNotConnectToWindowsUpdateInternetLocations : 1 TargetGroupEnabled : 1
TargetGroup : WorkstationsProd
NoAutoUpdate : 0
AUOptions : 3 - Notify before installation
ScheduledInstallDay : 0 - Every Day
ScheduledInstallTime : 3
UseWUServer : 1
AutoInstallMinorUpdates : 0
AlwaysAutoRebootAtScheduledTime : 0
DetectionFrequencyEnabled : 1
DetectionFrequency : 4Вывести текущие настройки windows update - Get-WUSettings

В данном примере клиент Windows Update на компьютере настроен с помощью GPO на получение обновлений с локального сервера обновлений WSUS.

Управление обновлениями Windows на удаленных компьютерах через PowerShell

Практически все командлеты модуля PSWindowsUpdate позволяют управлять обновлеями на удаленных компьютерах. Для этого используется атрибут
-Computername Host1, Host2, Host3
. На удаленных компьютерах должен быть включен и настроен WinRM (вручную или через GPO). Модуль PSWindowsUpdate можно использовать для удаленного управлений обновлениями Windows как на компьютерах в домене AD, так и в рабочей группе (потребует определенной настройки PowerShell Remoting).

Для удаленного управления обновлениями компьютерах, нужно добавить имена компьютеров доверенных хостов winrm, или настроить удаленное управление PSRemoting через WinRM HTTPS:

Или с помощью PowerShell:
Set-Item wsman:\localhost\client\TrustedHosts -Value wsk-w10BO1 -Force

С помощью Invoke-Command можно разрешить использовать модуль PSWindowsUpdate на удаленных компьютерах и открыть необходимые порты в Windows Defender Firewall (команда
Enable-WURemoting
):

Проверить список доступных обновлений на удаленном компьютере:

Get-WUList –ComputerName server2

Командлет Invoke-WUJob (ранее командлет назывался Invoke-WUInstall) создаст на удаленном компьютере задание планировщика, запускаемое от SYSTEM. Можно указать точное время для установки обновлений Windows:

Проверить статус задания установки обновлений:

Get-WUJob -ComputerName $ServerNames

Если команда вернет пустой список, значит задача установки на всех компьютерах выполнена.

Проверьте наличие обновления на нескольких удаленных компьютерах:

Получить дату последней установки обновлений на всех компьютерах в домене можно с помощью командлета Get-ADComputer из модуля AD PowerShell:

PowerShell модуль PSWindowsUpdate удобно использовать для загрузки и установки обновлений Windows из командной строки (единственный доступны вариант в случае установки обновлений на хосты без графического интерфейса: Windows Server Core и Hyper-V Server). Также этот модуль незаменим, когда нужно одновременно запустить и проконтролировать установку обновлений сразу на множестве серверов/рабочих станциях Windows.

Сканировать и загрузить обновления Windows с помощью PowerShell

Чтобы просканировать компьютер на сервере обновлений и вывести список обновлений, которые ему требуется, выполните команду:

Команда должна вывести список обновлений, которые нужно установить на вашем компьютере.

Поиск (сканирование) доступных обновлений windows: get-windowsupdate

Команда Get-WindowsUpdate при первом запуске может вернуть ошибку:

Value does not fall within the expected range.

Ошибка Get-WindowsUpdate - Value does not fall within the expected range.

Reset-WUComponent сбросить настройки windows update

Чтобы проверить, откуда получает ли Windows обновлений с серверов Windows Update в Интернете или локального WSUS, выполните команду:

Get-WUServiceManager - источникиа обновлений

В этом примере вы видите, компьютер настроен на получение обновлений с локального сервера WSUS (Windows Server Update Service = True). В этом случае вы должны увидеть список обновлений, одобренных для вашего компьютера на WSUS.

Если вы хотите просканировать ваш компьютер на серверах Microsoft Update в Интернете (кроме обновлений Windows на этих серверах содержатся обновления Office и других продуктов), выполните команду:

Вы получаете предупреждение:

Get-WUlist : Service Windows Update was not found on computer

Чтобы разрешить сканирование на Microsoft Update, выполните команду:

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

  • Категории (-NotCategory);
  • Названию (-NotTitle);
  • Номеру обновления (-NotKBArticleID).

Например, чтобы исключить из списка обновления драйверов, OneDrive, и одну конкретную KB:

Get-WUlist -NotCategory "Drivers" -NotTitle OneDrive -NotKBArticleID KB4533002

Get-WindowsUpdate -Download -AcceptAll

Windows загрузит все доступные патчи сервера обновлений (MSU и CAB файлы) в локальный каталог обновлений, но не запустит их автоматическую установку.

Get-WindowsUpdate скачать доступные обновления на диск