В этой статье мы рассмотрим, как обновить версию Windows PowerShell до актуальной 5.1 и установить (обновить) PowerShell Core 7.3. В предыдущей статье мы рассказывали, что на данный момент есть две ветки PowerShell:
- старая версия Windows PowerShell (максимальная версия 5.1, которая более не развивается);
- новая платформа PowerShell Core (сейчас доступна версия 7.3).
Несмотря на то, что нумерация версий PowerShell продолжается с 5.1 (6.0, 6.1, 7.0 и т.д.), это две разные платформы. Соответственно мы отдельно рассмотрим как обновить Windows PowerShell и PowerShell Core.
PowerShell Core 7.x максимально совместима с Windows PowerShell. Это означает, что вы можете запускать свои старые скрипты и командлеты в PowerShell Core.
Содержание:
- Обновление Windows PowerShell до 5.1
- Установка/обновление PowerShell Core 7.x
- Установка/обновление PowerShell Core на удаленных комьютерах
- Обновление PowerShell через Windows Update или WSUS
Обновление Windows PowerShell до 5.1
Во всех версиях, начиная с Windows 10 и Windows Server 2016, Windows PowerShell 5.1 уже установлен по-умолчанию.
В предыдущих версиях (Windows 7/8.1 и Windows 2008 R2/2012) обновление до PowerShell 5.1 нужно выполнять вручную. Например, в Windows Server 2012 R2 (Windows 8.1) установлен PowerShell 4.0.
Попробуем обновить версию Windows PowerShell в Windows Server 2012 R2 до версии 5.1.
Сначала проверьте текущую версию PowerShell (на скриншоте видно, что это PowerShell 4.0):
$PSVersionTable.PSVersion
Чтобы обновить вашу версию PowerShell до 5.1, нужно установить пакет Windows Management Framework (WMF) 5.1, который в свою очередь требует наличия .NET Framework 4.5.2 (или более поздней версии). Убедитесь, что у вас установлена версий .NET 4.5.2 или выше командой:
(Get-ItemProperty ‘HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full’ -Name Release).Release
В моем случае код 378675 говорит о том, что установлена версия .NET 4.5.1. Поэтому мне нужно скачать и установить более новую .NET Framework 4.8 (ссылка на офлайн установщик https://go.microsoft.com/fwlink/?linkid=2088631 —
ndp48-x86-x64-allos-enu.exe
).
Установите .NET 4.8 (потребуется перезагрузка).
Если установить WMF 5.1, но не установить .NET 4.5.2 (или более новый), часть функций PowerShell не будет работать.
Скачайте WMF 5.1 для Windows Server 2012 R2 —
Win8.1AndW2K12R2-KB3191564-x64.msu
(https://go.microsoft.com/fwlink/?linkid=839516).
Установите MSU файл Windows Management Framework 5.1.
После перезагрузки сервера, запустите консоль powershell.exe и убедитесь, что версия была обновлена до PowerShell 5.1.
Если у вас остались снятые с поддержки Windows Server 2008 R2 и Windows 7, вы можете обновить на них версию PowerShell с 2.0 до 5.1 аналогичным способом. Сначала устанавливается .Net Framework 4.5.2 (или выше) и затем WMF 5.1 (ссылки загрузки будут другими, чем для Windows Server 2012 R2).
Установка/обновление PowerShell Core 7.x
PowerShell Core является кроссплатформенной и находится в стадии активной разработки (в отличии от Windows PoweShell 5.1). По сути, PowerShell Core это новая платформа, которая устанавливается в операционной системе вместе с классическим Windows PowerShell. Т.е. нельзя обновить PowerShell 5.1 до PowerShell Core 7.1. PowerShell 7 устанавливается на компьютере отдельно от Windows PowerShell 5.1 (side by side).
На данный момент доступны версии PowerShell Core 6.x и 7.x. Рекомендуется всегда устанавливать последнюю версиях PowerShell (сейчас это 7.3), если вам не требуется особая совместимость с legacy скриптами.
Вы можете обновить (установить) версию PowerShell Core в Windows 10 и 11 несколькими способами:
- С помощью MSI установщика PowerShell Core, который можно скачать на GitHub
- С помощью менеджера пакетов WinGet
- С помощью магазина приложений Microsoft
Далее мы рассмотрим все эти способы на примере обновления PowerShell Core до 7.3 в Windows 10 22H2
Обновить PowerShell Core с помощью MSI установщика
Если вы хотите установить PowerShell Core с помощью MSI пакета, перейдите на старицу проекта https://github.com/PowerShell/PowerShell и скачайте установочный пакет для вашей версии ОС. На момент написания статьи последняя версия v7.3.3 Release of PowerShell от 24 февраля 2023 (например, PowerShell-7.3.3-win-x64.msi или PowerShell-7.3.3-win-x86.msi). Для продуктивной среды используйте Stable или LTS релизы.
Скачайте msi файл и установите его.
Доступны следующие опции установки:
- Add PowerShell to Path Environment Variable
- Register Windows Event Logging Manifest (для событий PowerShell будет создан отдельный журнал Event Viewer
%SystemRoot%\System32\Winevt\Logs\PowerShellCore%4Operational.evtx
) - Enable PowerShell Remoting (включает и настраивает WinRM для PowerShell Remoting)
- Add ‘Open here’ context menu to Explorer
- Add ‘Run with PowerShell 7’ context menu for PowerShell files
Далее вы можете включить автоматическое обновление PowerShell Core через WIndows Update/WSUS (рассмотрено ниже).
Для установки PowerShell Core из MSI пакета средствами SCCM/MDT/скриптами в тихом режиме можно использовать команду установки со следующими параметрами:
- ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL
- ADD_FILE_CONTEXT_MENU_RUNPOWERSHELL
- ENABLE_PSREMOTING
- REGISTER_MANIFEST
- ADD_PATH
- DISABLE_TELEMETRY
- USE_MU – использовать Microsoft Update для получения обновлений PSCore
- ENABLE_MU – разрешить обновление PowerShell Core через Windows Update
Например, команда установки может выглядеть так:
msiexec.exe /package PowerShell-7.3.3-win-x64.msi /quiet ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL=1 ENABLE_PSREMOTING=1 REGISTER_MANIFEST=1 ADD_PATH=1 ENABLE_MU=1 ADD_PATH=1
Вы можете обновить PowerShell непосредственно из консоли. Чтобы установить или обновиться до последней версии PoSh Core, выполните команду:
iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI"
Данная команда загружает установочный MSI файл PowerShell 7.3 с GitHub и запускает установку через MSI Installer.
После окончания установки открывается окно PowerShell Core (pwsh.exe), проверьте версию PowerShell и убедитесь, что теперь это PoSh 7.3.3.
Используем менеджер пакетов WinGet для установки/обновления PowerShell Core
Если у вас установлен пакетный менеджер WinGet, вы можете установить или обновить версию PowerShell до актуальной командой:
winget install --id Microsoft.Powershell --source winget
Либо можно установить конкретную версию PowerShell Core:
winget install --id=Microsoft.PowerShell -v "7.1.2" -e
При использовании менеджера пакетов Chocolatey, используйте команды (для 5.1):
choco install powershell -y
choco upgrade powershell -y
Для обновления PowerShell 7.x:
choco upgrade pwsh -y
Обратите внимание на каталоги различных версий PowerShell:
- Windows PowerShell 5.1:
$env:WINDIR\System32\WindowsPowerShell\v1.0
- PowerShell Core 6.x:
$env:ProgramFiles\PowerShell\6
- PowerShell 7.x:
$env:ProgramFiles\PowerShell\7
Если на компьютере был установлен PowerShell 6.x, то при установке PowerShell 7.3 каталог
$env:ProgramFiles\PowerShell\6
автоматически удаляется.
Обратите внимание, что имя исполняемого файла среды PowerShell изменился. Теперь это
c:\Program Files\PowerShell\7\pwsh.exe
. У него собственная иконка в меню Start.
- Для запуска Windows PowerShell, основанного на .NET Framework используется команда
powershell.exe
- Для запуска PowerShell Core, основанного на .NET Core, нужно использовать команду
pwsh.exe
Т.е. теперь на этом компьютере есть две версии: Windows PowerShell 5.1 и PowerShell Core 7.3.
Чтобы узнать версию PowerShell можно проверять версию файла pwsh.exe:
(Get-Command 'C:\Program Files\PowerShell\7\pwsh.exe').Version
Так можно проверить версию файла на удаленном компьютере:
Invoke-Command -Computername computer1 -Scriptblock {(Get-Command 'C:\Program Files\PowerShell\7\pwsh.exe').Version}
Чтобы запустить предыдущую версию PowerShell (например 4), используйте команду:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Version 4
Установка PowerShell Core через Microsoft Store
В Windows 10 и 11вы можете установить или обновить PowerShell через магазин приложений Microsoft Store. Приложение PowerShell можно найти в магазине вручную, или воспользуйтесь этой ссылкой.
Также вы можете установить магазинную версию PowerShell через WinGet:
winget search powershell --source msstore
winget install --id 9MZ1SNWT0N5D
Преимущество установки PowerShell Core через Microsoft Store в том, что магазин прилжений будет автоматически контролировать установленную версию PowerShell и автоматически устанавливать обновления по мере их появления.
Вы можете проверить, установлена ли у вас Store версия PowerShell Coreс помощью команды:
Get-AppPackage Microsoft.PowerShell
В этом примере пакет Microsoft.PowerShell_7.3.3.0_x64__8wekyb3d8bbwe установлен.
Но есть и недостатки, связанные с тем, что такой PowerShell будет запускаться в песочнице.
Установка/обновление PowerShell Core на удаленных комьютерах
Рассмотрим два сценария установки или обновления версии PowerShell Core на множестве компьютерах.
Обновление PowerShell Core с помощью GPO
В домене Active Directory вы можете централизованно установить и обновить PowerShell Core с помощью групповой политики. Воспользуйтесь возможностями установки программ с помощью MSI пакетов в GPO.
- Скачайте установочный MSI файл PowerShell и скопируйте его в каталог SYSVOL на контроллере домена;
- Откройте консоль управления доменными GPO (
gpmc.msc
), создайте новую GPO и назначьте ее на OU с компьютерами и серверами; - Перейдите в раздел GPO Computer Configuration –> Software Settings, создайте новый пакет и укажите для него путь к установочному MSI файлу PowerShell в SYSVOL;
Для более тонкого нацеливания политики на клиентов можно использовать WMI фильтры GPO.
- Для обновления групповых политик установки ПО нужно перезагрузить компьютеры. Во время загрузки на всех компьютерах будет установлена новая версия PowerShell.
Обновление PowerShell на удаленных компьютерах из командной строки
Вы можете обновлять PowerShell на удаленных компьютерах из командной строки.
- Первый способ позволяет удаленно обновить PowerShell на компьютере с помощью MSI установщика в сетевом каталоге:
Invoke-Command -ComputerName dc01 -ScriptBlock {Start-Process msiexec.exe -ArgumentList '/package "\\srv1\share\PowerShell-7.3.3-win-x64.msi" /quiet ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL=1 ENABLE_PSREMOTING=1 REGISTER_MANIFEST=1' -Wait}
- Следующий скрипт позволит выбрать все активные компьютеры с Windows 10 из домена Active Directory и запустить на каждом из них загрузку и установку PowerShell Core:
$creds = $(Get-Credential)
$computers = Get-ADComputer -Filter 'operatingsystem -like "*Windows 10*" -and enabled -eq "true"'
ForEach ($computer in $computers) {
Invoke-Command -ComputerName $computer -Credential $creds {iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI -Quiet"}
}
Будьте внимательными при использовании команд PowerShell Remoting при подключении к удаленным компьютерам (Enter-PSSession, Invoke-Command). Если вам нужно подключиться к точке управления PowerShell 7 нужно использовать команду:
Enter-PSSession -ComputerName dc01 -ConfigurationName "powershell.7"
Иначе вы подключитесь к точке PowerShell Remoting 5.1.
Обновление PowerShell в Linux дистрибутивах чаще проще всего выполняется через нативный менеджер пакетов.
Обновление PowerShell через Windows Update или WSUS
До версии PowerShell Core 7.2 не поддерживалось автоматическое обновление pwsh.exe. После выхода нового релиза в консоли появилось уведомление:
A new PowerShell stable release is available. Upgrade now, or check out the release page at: https://aka.ms/PowerShell-Release?tag=v7.1.3
Начиная с версии 7.2, PowerShell Core поддерживает автоматическое обновление через Windows Update ( Microsoft Update, Windows Update for Business, внутренний WSUS сервер или SCCM). Для этого при установке MSI пакета нужно включить соответствующие опции.
Проверьте, что в панели управления Settings -> Update and Security -> Windows Update -> Advanced Options теперь включена опция Receive updates for other Microsoft products when you update Windows.
Теперь, когда вы нажимаете кнопку Check for Updates или запускаете сканирование обновлений через модуль PSWindowsUpdate, вы также будете получать обновления для PowerShell Core.
В этой статье расскажем, как обновить Windows PowerShell до актуальной версии 5.1 и установить (обновить) PowerShell Core 7.3. На данный момент существуют две ветки PowerShell:
— Старая версия Windows PowerShell (максимальная версия 5.1, которая больше не развивается).
— Новая платформа PowerShell Core (доступна версия 7.3).
Несмотря на то, что нумерация версий PowerShell продолжается с 5.1 (6.0, 6.1, 7.0 и т.д.), это две разные платформы.
Мы рассмотрим, как обновить Windows PowerShell и PowerShell Core.
PowerShell Core 7.x совместима с Windows PowerShell, что означает, что вы можете запускать старые скрипты и командлеты в PowerShell Core.
Приобрести оригинальные ключи активации Windows всегда можно у нас в каталоге от 1099 ₽
Обновление Windows PowerShell до 5.1
Во всех версиях, начиная с Windows 10 и Windows Server 2016, Windows PowerShell 5.1 уже установлен по умолчанию.
В более ранних версиях (Windows 7/8.1 и Windows Server 2008 R2/2012) обновление до PowerShell 5.1 выполняется вручную. Например, в Windows Server 2012 R2 (Windows 8.1) установлена PowerShell 4.0.
Попробуем обновить версию PowerShell в Windows Server 2012 R2 до 5.1.
1. Проверьте текущую версию PowerShell:
$PSVersionTable.PSVersion
2. Для обновления PowerShell до версии 5.1 установите Windows Management Framework (WMF) 5.1, который требует .NET Framework 4.5.2 или выше. Чтобы убедиться, что у вас установлена нужная версия .NET, выполните команду:
(Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full' -Name Release).Release
3. Если у вас устаревшая версия .NET (например, 4.5.1), скачайте и установите NET Framework 4.8
4. После установки .NET 4.8 (потребуется перезагрузка) скачайте WMF 5.1 для Windows Server 2012 R2
5. Установите MSU файл Windows Management Framework 5.1.
6. Перезагрузите сервер, затем запустите консоль powershell.exe и убедитесь, что версия обновлена до PowerShell 5.1:
$PSVersionTable.PSVersion
Если у вас Windows Server 2008 R2 или Windows 7, вы также можете обновить PowerShell до 5.1 аналогичным способом: сначала установите .NET Framework 4.5.2 или выше, а затем установите WMF 5.1.
Установка/обновление PowerShell Core 7.x
PowerShell Core — это кроссплатформенная среда, которая активно развивается в отличие от Windows PowerShell 5.1. Она устанавливается отдельно от Windows PowerShell, поэтому обновление Windows PowerShell 5.1 до PowerShell Core невозможно.
На данный момент доступны версии PowerShell Core 6.x и 7.x. Рекомендуется использовать последнюю версию PowerShell Core (сейчас это 7.3), если вам не требуется особая совместимость с устаревшими скриптами.
Существует несколько способов обновления или установки PowerShell Core в Windows 10 и 11:
— С помощью MSI установщика PowerShell Core (скачивается на GitHub).
— С помощью менеджера пакетов WinGet.
— Через Microsoft Store.
Обновление PowerShell Core с помощью MSI установщика
1. Перейдите на страницу проекта PowerShell на GitHub и скачайте последнюю версию установочного пакета MSI.
2. Установите MSI файл. Во время установки доступны следующие опции:
— Add PowerShell to Path Environment Variable — добавляет PowerShell в переменные окружения.
— Register Windows Event Logging Manifest — регистрирует журнал событий для PowerShell.
— Enable PowerShell Remoting — включает удалённое управление через WinRM.
— Add ‘Open here’ context menu to Explorer — добавляет пункт в контекстное меню Проводника.
— Add ‘Run with PowerShell 7’ context menu for PowerShell files — добавляет пункт для запуска скриптов через PowerShell 7.
3. Для автоматического обновления PowerShell Core через Windows Update или WSUS активируйте соответствующие опции.
Обновление PowerShell Core через WinGet
1. Если у вас установлен WinGet, вы можете установить или обновить PowerShell до актуальной версии командой:
winget install --id Microsoft.Powershell --source winget
2. Если нужно установить конкретную версию PowerShell Core, используйте:
winget install --id=Microsoft.PowerShell -v "7.1.2" -e
Для установки PowerShell Core из MSI пакета средствами SCCM/MDT/скриптами в тихом режиме можно использовать команду установки со следующими параметрами:
ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL
ADD_FILE_CONTEXT_MENU_RUNPOWERSHELL
ENABLE_PSREMOTING
REGISTER_MANIFEST
ADD_PATH
DISABLE_TELEMETRY
USE_MU – использовать Microsoft Update для получения обновлений PSCore
ENABLE_MU – разрешить обновление PowerShell Core через Windows UpdateНапример, команда установки может выглядеть так:
msiexec.exe /package PowerShell-7.3.3-win-x64.msi /quiet ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL=1 ENABLE_PSREMOTING=1 REGISTER_MANIFEST=1 ADD_PATH=1 ENABLE_MU=1 ADD_PATH=1
Вы можете обновить PowerShell прямо из консоли. Для этого выполните следующую команду, которая загрузит и установит последнюю версию PowerShell Core с использованием MSI установщика:
iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI"
Эта команда загружает установочный MSI файл PowerShell 7.3 с GitHub и автоматически запускает установку через MSI Installer.
После завершения установки откроется окно PowerShell Core (pwsh.exe). Проверьте текущую версию PowerShell, чтобы убедиться, что теперь установлена последняя версия 7.3.3:
$PSVersionTable.PSVersion
Использование WinGet для установки или обновления PowerShell Core
Если у вас установлен пакетный менеджер WinGet, вы можете установить или обновить PowerShell до актуальной версии с помощью следующей команды:
winget install --id Microsoft.Powershell --source winget
Если нужно установить конкретную версию PowerShell Core, выполните команду:
winget install --id=Microsoft.PowerShell -v "7.1.2" -e
Использование Chocolatey для установки или обновления PowerShell
Если вы используете менеджер пакетов Chocolatey, для установки или обновления PowerShell 5.1 используйте следующие команды:
choco install powershell -y
choco upgrade powershell -y
Для обновления PowerShell 7.x:
choco upgrade pwsh -y
Важные каталоги PowerShell
Обратите внимание на местоположение файлов различных версий PowerShell:
— Windows PowerShell 5.1: $env:WINDIR\System32\WindowsPowerShell\v1.0
— PowerShell Core 6.x: $env:ProgramFiles\PowerShell\6
— PowerShell 7.x: $env:ProgramFiles\PowerShell\7
При установке PowerShell 7.3, если на компьютере уже была установлена версия 6.x, каталог $env:ProgramFiles\PowerShell\6 автоматически удаляется.
Также обратите внимание, что исполняемый файл PowerShell Core теперь называется pwsh.exe и находится в каталоге c:\Program Files\PowerShell\7\pwsh.exe. У него есть собственная иконка в меню Пуск.
— Для запуска Windows PowerShell (на базе .NET Framework) используйте команду:
powershell.exe
— Для запуска PowerShell Core (на базе .NET Core) используйте команду:
pwsh.exe
Использование двух версий PowerShell
Теперь на вашем компьютере могут быть установлены обе версии PowerShell: Windows PowerShell 5.1 и PowerShell Core 7.3
Чтобы проверить версию PowerShell Core, вы можете выполнить следующую команду:
(Get-Command 'C:\Program Files\PowerShell\7\pwsh.exe').Version
Также можно проверить версию PowerShell на удалённом компьютере:
Invoke-Command -ComputerName computer1 -Scriptblock {(Get-Command 'C:\Program Files\PowerShell\7\pwsh.exe').Version}
Запуск предыдущих версий PowerShell
Если вам нужно запустить предыдущую версию PowerShell, например PowerShell 4, используйте следующую команду:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Version 4
Обновление PowerShell Core через Microsoft Store
В Windows 10 и 11 вы можете установить PowerShell через Microsoft Store. Приложение PowerShell можно найти вручную, или установить через WinGet:
winget search powershell --source msstore
winget install --id 9MZ1SNWT0N5D
Преимущество этого способа заключается в том, что Microsoft Store будет автоматически следить за обновлениями и устанавливать их по мере появления.
Вы можете проверить, установлена ли у вас Store версия PowerShell Coreс помощью команды:
Get-AppPackage Microsoft.PowerShell
В этом примере пакет Microsoft.PowerShell_7.3.3.0_x64__8wekyb3d8bbwe установлен.
Но есть и недостатки, связанные с тем, что такой PowerShell будет запускаться в песочнице.
Установка/обновление PowerShell Core на удалённых компьютерах
Обновление PowerShell Core с помощью GPO
В домене Active Directory вы можете централизованно установить или обновить PowerShell Core с помощью групповой политики (GPO):
1. Скачайте MSI файл PowerShell и скопируйте его в каталог SYSVOL на контроллере домена.
2. Откройте консоль управления GPO (gpmc.msc), создайте новую политику и назначьте её на OU с компьютерами.
3. В разделе Computer Configuration -> Software Settings создайте новый пакет и укажите путь к MSI файлу PowerShell в каталоге SYSVOL.
4. Для обновления групповых политик установки ПО нужно перезагрузить компьютеры. Во время загрузки на всех компьютерах будет установлена новая версия PowerShell.
Обновление PowerShell на удалённых компьютерах из командной строки
Вы можете обновлять PowerShell на удалённых компьютерах через консоль. Пример команды для установки PowerShell с помощью MSI установщика:
Invoke-Command -ComputerName dc01 -ScriptBlock {Start-Process msiexec.exe -ArgumentList '/package "\\srv1\share\PowerShell-7.3.3-win-x64.msi" /quiet ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL=1 ENABLE_PSREMOTING=1 REGISTER_MANIFEST=1' -Wait}
Следующий скрипт позволит выбрать все активные компьютеры с Windows 10 из домена Active Directory и запустить на каждом из них загрузку и установку PowerShell Core:
$creds = $(Get-Credential)
$computers = Get-ADComputer -Filter 'operatingsystem -like "*Windows 10*" -and enabled -eq "true"'
ForEach ($computer in $computers) {
Invoke-Command -ComputerName $computer -Credential $creds {iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI -Quiet"}
}
Для использование командлета GetADComputer на компьютере должен быть установлен модуль AD PowerShell.
Будьте внимательными при использовании команд PowerShell Remoting при подключении к удаленным компьютерам (Enter-PSSession, Invoke-Command). Если вам нужно подключиться к точке управления PowerShell 7 нужно использовать команду:
Enter-PSSession -ComputerName dc01 -ConfigurationName "powershell.7"
Иначе вы подключитесь к точке PowerShell Remoting 5.1.
Обновление PowerShell через Windows Update или WSUS
Начиная с версии 7.2, PowerShell Core поддерживает автоматическое обновление через Windows Update. Для этого включите опции автоматического обновления при установке MSI пакета.
Первая опция разрешает автоматическое обновление PowerShell через любой канал (включает параметр UseMU =1 в ветке HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShellCore)
Второй чекбокс – разрешает получать обновления для всего ПО Microsoft, не только для Windows. Если опция отключена, вы не будете получать обновления PowerShell с Microsoft Update, но можете получать их с вашего WSUS/SCCM (параметр реестра registeredwithAU=1 в HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Services\7971F918-A847-4430-9279-4A52D1EFE18D)
Для проверки наличия обновлений откройте Настройки > Обновление и безопасность > Windows Update > Дополнительные параметры и убедитесь, что активирована опция Получать обновления для других продуктов Microsoft.
Теперь при проверке обновлений через Windows Update или через модуль PSWindowsUpdate, вы будете получать обновления для PowerShell Core.
Таким образом, вы можете выбрать удобный для вас способ обновления Windows PowerShell и PowerShell Core, будь то использование MSI пакета, WinGet, Microsoft Store, или групповых политик.
В состав стандартных средств операционной системы Windows Server 2008 R2 входит powershell версии 2.0. Вторая версия — очень древняя и не содержит большого количества полезных функций. Для обновления версии до 5.1 нужно установить .NET Framework версии 4.x (желательно последний) и Windows Management Framework (WMF) версии 5.1 (KB3191566).
Смотрим текущую версию powershell:
$PSVersionTable
Строчка PSVersion.
Скачиваем и устанавливаем .NET Framework. Оф.сайт, зеркало.
Скачиваем и устанавливаем WMF (KB3191566). Оф. сайт, зеркало.
Перезагружаем сервер.
Проверяем версию:
$PSVersionTable
Должна быть 5.1
This article describes how to update Windows PowerShell to the latest version 5.1 and how to install (upgrade) PowerShell Core 7.3. There are currently two branches of PowerShell:
- The classic Windows PowerShell (the maximum version is 5.1, which is no longer being developed.);
- The new PowerShell Core platform (version 7.3 is available now).
Although the PowerShell version numbering continues from 5.1 (6.0, 6.1, 7.0, 7.1, and so on), they are two different platforms. Therefore, updating Windows PowerShell and PowerShell Core will be covered separately.
PowerShell Core 7.x is the version that is most compatible with classic Windows PowerShell. This means that you can easily run your old PS1 script files and cmdlets in PowerShell Core.
Contents:
- Upgrading to Windows PowerShell 5.1
- How to Install or Update PowerShell Core 7?
- Installing/Updating PowerShell Core on Remote Computers
- Updating PowerShell via Windows Update or WSUS
Upgrading to Windows PowerShell 5.1
Windows PowerShell 5.1 is already installed by default in all versions, starting with Windows 10 and Windows Server 2016.
You must manually upgrade to PowerShell 5.1 for earlier versions (Windows 7/8.1 and Windows 2008 R2/2012). For example, Windows Server 2012 R2 (Windows 8.1) has PowerShell 4.0 installed.
Let’s try upgrading the Windows PowerShell version to 5.1 in Windows Server 2012 R2.
First, check the current PowerShell version (the screenshot shows that it’s PowerShell 4.0):
$PSVersionTable.PSVersion
To upgrade your PowerShell version to 5.1, install the Windows Management Framework 5.1, which requires the .NET Framework 4.5.2 (or later). Make sure that .NET 4.5.2 or higher is installed using this command:
(Get-ItemProperty ‘HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full’ -Name Release).Release
In my case, the release version 378675
means that the .NET Framework version 4.5.1 is installed. So, I have to download and install the latest .NET Framework 4.8 (here is the link to the offline installer: https://go.microsoft.com/fwlink/?linkid=2088631 — ndp48-x86-x64-allos-enu.exe
).
Install the .NET 4.8 package (you will need to restart your computer):
If you install WMF 5.1 without .NET 4.5.2, some PowerShell features will not be available.
Download WMF 5.1 for Windows Server 2012 R2 — Win8.1AndW2K12R2-KB3191564-x64.msu
(https://go.microsoft.com/fwlink/?linkid=839516).
Install the Windows Management Framework 5.1 from the MSU file.
After you restart the server, open the powershell.exe console and make sure that the PowerShell version has been updated to 5.1.
If you have unsupported Windows 7 or Windows Server 2008 R2, you can upgrade the PowerShell version from 2.0 to 5.1 in the same way. First, install .Net Framework 4.5.2 (or newer), then WMF 5.1 (the download links will be different from those for Windows Server 2012 R2).
How to Install or Update PowerShell Core 7?
PowerShell Core is cross-platform and under active development (unlike Windows PowerShell 5.1). Actually, PowerShell Core is a new platform installed on the operating system alongside the classic Windows PowerShell. This means that you cannot upgrade from PowerShell 5.1 to PowerShell Core 7.3. PowerShell 7.x is installed on your computer separately from Windows PowerShell 5.1 (side-by-side).
PowerShell Core 6.x and 7.x are available at this time. It is recommended that you always install the latest version of PowerShell (currently 7.3) unless you need special compatibility with legacy scripts.
There are several ways to upgrade (install) the PowerShell Core version on Windows 10 and 11:
- Use the PowerShell Core MSI installer, which is available to download from GitHub;
- Using the built-in Windows 10/11 package manager WinGet;
- Using the Microsoft Store.
Next, using the example of updating PowerShell Core to 7.3 on Windows 10 22H2, we will look at all of these methods.
Upgrading the PowerShell Core Using MSI installation
If you want to install PowerShell Core using the MSI package, go to the project page https://github.com/PowerShell/PowerShell and download the installation package for your OS version. At the time of writing, the most recent release of PowerShell is v7.3.3, dated 24 February 2023 (for example, PowerShell-7.3.3-win-x64.msi
or PowerShell-7.3.3-win-x86.msi
). Use only stable or LTS releases for a production environment.
Download the MSI file and install it.
The following installation options are available:
- Add PowerShell to Path Environment Variable
- Register Windows Event Logging Manifest (a separate Event Viewer log is created for PowerShell events.
%SystemRoot%\System32\Winevt\Logs\PowerShellCore%4Operational.evtx
) - Enable PowerShell Remoting (enables and configures WinRM for PowerShell Remoting)
- Add ‘Open here’ context menu to Explorer
- Add ‘Run with PowerShell 7’ context menu for PowerShell files
Next, you can enable automatic updates of the PowerShell Core through Windows Update/WSUS (see below).
To install PowerShell Core from an MSI package using SCCM/MDT/scripts in quiet mode, you can use a command with the following parameters:
- ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL
- ADD_FILE_CONTEXT_MENU_RUNPOWERSHELL
- ENABLE_PSREMOTING
- REGISTER_MANIFEST
- ADD_PATH
- DISABLE_TELEMETRY
- USE_MU – use the Microsoft Update to get PSCore updates
- ENABLE_MU – allow the PowerShell Core to be updated through Windows Update
For example, the command for a silent installation might look something like this:
msiexec.exe /package PowerShell-7.3.3-win-x64.msi /quiet ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL=1 ENABLE_PSREMOTING=1 REGISTER_MANIFEST=1 ADD_PATH=1 ENABLE_MU=1 ADD_PATH=1
You can upgrade PowerShell directly from the console. To install or upgrade to the latest version of PowerShell Core, run the following command:
iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI"
This command downloads the PowerShell 7.3 MSI file from GitHub and then starts the installation via the MSI installer.
When the installation is complete, the PowerShell Core (pwsh.exe) window appears. Check the PowerShell version to ensure that it is updated to PoSh 7.3.3.
Using WinGet Package Manager to Install or Update PowerShell Core
If you have the WinGet package manager installed, you can install or update your PowerShell version to the latest command:
winget install --id Microsoft.Powershell --source winget
Or, you can install a specific version of PowerShell Core:
winget install --id=Microsoft.PowerShell -v "7.1.2" -e
If you have the Chocolatey package manager installed, use the commands (for 5.1):
choco install powershell -y
choco upgrade powershell -y
or for PowerShell 7.x:
choco install pwsh -y
choco install pwsh -y
Note the default directories for different versions of PowerShell:
- Windows PowerShell 5.1:
$env:WINDIR\System32\WindowsPowerShell\v1.0
- PowerShell Core 6.x:
$env:ProgramFiles\PowerShell\6
- PowerShell Core 7.x:
$env:ProgramFiles\PowerShell\7
If PowerShell 6.x was installed on your computer, the $env:ProgramFiles\PowerShell\6
directory is automatically removed when you install PowerShell 7.3.
Note that the name of the PowerShell executable file has changed. In PowerShell Core, it is c:\Program Files\PowerShell\7\pwsh.exe. It has its icon in the Start menu.
- To run .NET Framework-based Windows PowerShell, the
powershell.exe
command is used - To run .NET Core-based PowerShell Core, use the
pwsh.exe
This means that you have both Windows PowerShell 5.1 and PowerShell Core 7.3 installed on your computer.
To find the version and build of PowerShell that is installed on your device, you can check the version of the pwsh.exe file:
(Get-Command 'C:\Program Files\PowerShell\7\pwsh.exe').Version
This is how you can check the version of a file on a remote computer:
Invoke-Command -Computername computer1 -Scriptblock {(Get-Command 'C:\Program Files\PowerShell\7\pwsh.exe').Version}
Windows PowerShell provides a special backward compatibility mode that allows you to run an older version of PowerShell even if you have newer versions installed. You can use the following command to run a specific version of PowerShell example, 4.0):
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Version 4
Install PowerShell Core on Windows 10 and 11 via Microsoft Store
On Windows 10 and 11, you can install or update PowerShell through the Microsoft Store. You can manually find the PowerShell app in the Store or use this link.
You can also use WinGet to install the Store version of PowerShell:
winget search powershell --source msstore
winget install --id 9MZ1SNWT0N5D
The advantage of installing PowerShell Core from the Microsoft Store is that the App Store automatically checks your installed version of PowerShell and automatically installs updates as they become available.
To verify that you have installed the Store version of PowerShell Core, use the command:
Get-AppPackage Microsoft.PowerShell
The Microsoft.PowerShell_7.3.3.0_x64__8wekyb3d8bbwe package is installed in this example.
However, there are also drawbacks to the fact that such an instance of PowerShell will be running in a sandbox environment.
Installing/Updating PowerShell Core on Remote Computers
Consider two scenarios for installing or updating the PowerShell Core on multiple remote computers.
Deploying PowerShell Core with Group Policy
You can use Group Policy to centrally deploy and update PowerShell Core in an Active Directory domain. Use the features of the GPO to deploy MSI packages to domain computers.
- Download the PowerShell MSI installation file and copy it to the SYSVOL directory on the domain controller;
- Open the Domain Group Policy Management Console (
gpmc.msc
), create a new GPO and link it to the OU with computers and servers; - Go to the GPO section Computer Configuration -> Software Settings, create a new package, and specify the path to the PowerShell MSI installation file in the SYSVOL folder in the domain (use the UNC path);
To more accurately target your policy to domain devices, you can use the GPO WMI filters.
- To update the Group Policy settings for the software installation, you must restart the computers. The new version of PowerShell will be installed on all computers at startup.
How to Update PowerShell on a Remote Computer from the Command Prompt?
You can use the command line prompt to update PowerShell on a remote computer.
- The first method uses an MSI installer in a shared network folder to remotely update PowerShell on a computer:
Invoke-Command -ComputerName mun-srv01 -ScriptBlock {Start-Process msiexec.exe -ArgumentList '/package "\\mun-fs01\install\PowerShell-7.3.3-win-x64.msi" /quiet ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL=1 ENABLE_PSREMOTING=1 REGISTER_MANIFEST=1' -Wait}
- The following script selects all enabled computers running Windows 10 from the Active Directory domain and starts downloading and installing PowerShell Core on each of them:
$ADComputers = Get-ADComputer -Filter 'operatingsystem -like "*Windows 10*" -and enabled -eq "true"'
ForEach ($computer in $ADcomputers) {
Invoke-Command -ComputerName $computer {iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI -Quiet"}
}
Take care when using PowerShell Remoting commands when connecting to remote computers (with the Enter-PSSession
and Invoke-Command
cmdlets). If you need to connect to a PowerShell 7 endpoint, you must use the command:
Enter-PSSession -ComputerName dc01 -ConfigurationName "powershell.7"
Otherwise, you will connect to the PowerShell Remoting 5.1 endpoint.
Updating PowerShell via Windows Update or WSUS
Before PowerShell Core version 7.2, pwsh.exe was not automatically updated. There was only a notification in the console after the release of a new version:
A new PowerShell stable release is available. Upgrade now, or check out the release page at: https://aka.ms/PowerShell-Release?tag=v7.1.3
Starting with version 7.2, PowerShell Core supports automatic updates through Windows Update (Microsoft Update, Windows Update for Business, internal WSUS server, or SCCM). To do this, you must enable the appropriate options during the installation of the MSI package.
Check that the Receive updates for other Microsoft products when you update Windows option is now enabled under Settings -> Update and Security -> Windows Update -> Advanced options.
Now, when you click the Check for Updates button or run an update scan through the PSWindowsUpdate module, you will also receive updates for PowerShell Core.
Question
How upgrade Powershell version on Windows Server 2008 R2
On Windows Server 2008 R2 you have Powershell 2.0 on board. There are plenty of reasons to update them to new version 5.0. Fortunately Windows Server 2008 and Windows 7 supports newest release. How upgrade Powershell version on Windows Server 2008 R2?
Answer
To answer the question what are the benefits of upgrading Powershell to newest version please see related information:
- What’s new in Powershell 5.0 – LINK
- What’s new in ISE 5.0 – LINK
Of course it’s worth How to upgrade?
Requirements
At the beginning check already installed version of Powershell by starting them and type: Get-Host command. You should see following window.
Version 2.0 is visible. You need to download and install 3 things for upgrading Powershell from 2.0 to 5.0. First of all download source files:
- .NET Framework 4.5.2 – LINK
- Windows Management Framework 4.0 – LINK
- Windows Management Framework 5.0 – LINK
Make sure that system is updated and no new KB waiting for installation.
Installation
Installation should be performed in following steps:
That’s it! Now you have successfully installed new version of Powershell. Check it once gain typing Get-Host in PS command line.
Rollback
In any case of situation where rollback is needed few actions should be taken to uninstall WMF 5.0, WFM 4.0 and .NET Framework 4.5.2. To do this execute following steps:
- Uninstall KB3134758 which is WMF 5.0 and KB2819745 which is WMF 4.0,
- Remove .NET Framework 4.5.2.
After that system will be available with default Powershell 2.0. There is also possibility to install version 3.0 but it’s not needed in upgrade path.