В windows server 2016 должна быть включена транскрипция power shell

В этой статье мы рассмотрим, как обновить версию 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

Во всех версиях, начиная с 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

Чтобы обновить вашу версию 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

проверить версию .net

Установите .NET 4.8 (потребуется перезагрузка).

офлайн установка .NET Framework 4.8

Если установить WMF 5.1, но не установить .NET 4.5.2 (или более новый), часть функций PowerShell не будет работать.

Установите MSU файл Windows Management Framework 5.1.

установка Windows Management Framework 5.1 kb3191564

После перезагрузки сервера, запустите консоль powershell.exe и убедитесь, что версия была обновлена до PowerShell 5.1.

обновление версии windows powershell до 5.1 в windows server 2012 r2

Если у вас остались снятые с поддержки 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 установщика

скачать MSI установщик PowerShell для windows

Доступны следующие опции установки:

  • 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 из msi пакета

Далее вы можете включить автоматическое обновление PowerShell Core через WIndows Update/WSUS (рассмотрено ниже).

разрешить автоматическое обновление powershell core 7.2+

Для установки 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, выполните команду:

Данная команда загружает установочный MSI файл PowerShell 7.3 с GitHub и запускает установку через MSI Installer.

install-powershell.ps1 скрипт обновления powershell

После окончания установки открывается окно PowerShell Core (pwsh.exe), проверьте версию PowerShell и убедитесь, что теперь это PoSh 7.3.3.

проверить что powershell core обновлен в windows

Используем менеджер пакетов 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

powershell core 7 в windows 10

Т.е. теперь на этом компьютере есть две версии: Windows PowerShell 5.1 и PowerShell Core 7.3.

две версии powershell на компьютере core и desktop

Чтобы узнать версию PowerShell можно проверять версию файла pwsh.exe:

(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с помощью команды:

В этом примере пакет Microsoft.PowerShell_7.3.3.0_x64__8wekyb3d8bbwe установлен.

appx приложение Microsoft.PowerShell_7.3.3.0_x64__8wekyb3d8bbwe в microsoft store

Но есть и недостатки, связанные с тем, что такой PowerShell будет запускаться в песочнице.

ustanovkaобновление powershell core в windows 10 через microsoft store

Установка/обновление PowerShell Core на удаленных комьютерах

Рассмотрим два сценария установки или обновления версии PowerShell Core на множестве компьютерах.

Обновление PowerShell Core с помощью GPO

В домене Active Directory вы можете централизованно установить и обновить PowerShell Core с помощью групповой политики. Воспользуйтесь возможностями установки программ с помощью MSI пакетов в GPO.

  1. Скачайте установочный MSI файл PowerShell и скопируйте его в каталог SYSVOL на контроллере домена;
  2. Откройте консоль управления доменными GPO (
    gpmc.msc
    ), создайте новую GPO и назначьте ее на OU с компьютерами и серверами;
  3. Перейдите в раздел GPO Computer Configuration –> Software Settings, создайте новый пакет и укажите для него путь к установочному MSI файлу PowerShell в SYSVOL; обновление powershell в домене через gpo

    Для более тонкого нацеливания политики на клиентов можно использовать WMI фильтры GPO.

  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"}
    }

Будьте внимательными при использовании команд 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

:/>  20 важных нюансов работы с iCloud. Например, как расширить хранилище больше максимума

Начиная с версии 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.

Разрешить Windows получаить обнволения с Windows Update для других продуктов

Теперь, когда вы нажимаете кнопку Check for Updates или запускаете сканирование обновлений через модуль PSWindowsUpdate, вы также будете получать обновления для PowerShell Core.

проверить новые обновления в windows

В windows server 2016 должна быть включена транскрипция power shell

Windows
Значок отображаемых платформ

windows
mac
android

Значок поиска

Windows PowerShell icon

В windows server 2016 должна быть включена транскрипция power shell

Информация о Windows PowerShell 7.4.3

В windows server 2016 должна быть включена транскрипция power shellЛицензияБесплатно
В windows server 2016 должна быть включена транскрипция power shellОСWindows
В windows server 2016 должна быть включена транскрипция power shellРазделОбщие
В windows server 2016 должна быть включена транскрипция power shellЯзык Pусский
В windows server 2016 должна быть включена транскрипция power shellАвтор
Microsoft
В windows server 2016 должна быть включена транскрипция power shellЗагрузки186,685
В windows server 2016 должна быть включена транскрипция power shellДата19 июн 2024
В windows server 2016 должна быть включена транскрипция power shellВозрастные ограниченияНе указано
В windows server 2016 должна быть включена транскрипция power shellРекламаНе указано
В windows server 2016 должна быть включена транскрипция power shellПочему это приложение опубликовано на Uptodown?
(Больше информации)

Предыдущие версии

22 мая 2024

2 янв 2024

27 окт 2023

22 авг 2023

3 июл 2023

11 ноя 2022

Оценить это приложение

Рейтинг

Другие приложения автора

Microsoft Office 2019 icon

Установите Word, Excel и PowerPoint с Office 2019

Windows 10 icon

Попробуйте новую версию Windows еще до официального выхода

Microsoft Office 2016 icon

Новая версия самого популярного офисного пакета

Windows 8 (64 bits) icon

Новая версия Windows – откройте новые возможности!

Windows 11 icon
Microsoft Office 2021 icon

Версии Word, Excel, PowerPoint и Outlook 2021 года

DirectX icon

Оптимальная производительность для мультимедийных приложений

HEIF Image Extensions icon

Официальное расширение для открытия файлов в формате HEIF в Windows

Python icon

Объектно-ориентированный динамический язык программирования

Visual Studio Code icon

Многоплатформенный редактор кода для Microsoft

Atom icon

Полнофункциональный текстовый редактор для программистов от GitHub

Android Studio icon

Новая среда программирования для Android

Android SDK icon

Среда для программирования под Android

PyCharm Professional icon
Microsoft .NET Desktop Runtime icon

Запускайте приложения, созданные с помощью .NET в Windows

GitHub Desktop icon

Разрабатывайте в Windows, делитесь в GitHub

WinHex icon

Полнофункциональный шестнадцатеричный редактор

x64dbg icon

32-разрядный и 64-разрядный отладчик для Windows

Postman icon
Navicat Premium icon
DBeaver icon

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

Vim icon
Visual Studio Community icon

Мультиплатформенная среда разработки от Microsoft

WYSIWYG Web Builder icon

Простой редактор веб-страниц со встроенным FTP-клиентом

PowerShell
В windows server 2016 должна быть включена транскрипция power shell
В windows server 2016 должна быть включена транскрипция power shell

Screenshot of a PowerShell 7 session in Windows Terminal

ParadigmImperative, pipeline, object-oriented, functional and reflective
Designed byJeffrey Snover, Bruce Payette, James Truher (et al.)
DeveloperMicrosoft
First appearedNovember 14, 2006; 17 years ago
Stable release
Typing disciplineStrong, safe, implicit and dynamic
Implementation languageC#
PlatformPowerShell: .NET
Windows PowerShell: .NET Framework
OS
LicenseMIT License[2] (but the Windows component remains proprietary)
Filename extensions
  • .ps1 (Script)
  • .ps1xml (XML Document)
  • .psc1 (Console File)
  • .psd1 (Data File)
  • .psm1 (Script Module)
  • .pssc (Session Configuration File)
  • .psrc (Role Capability File)
  • .cdxml (Cmdlet Definition XML Document)
Website
Influenced by
Python, Ksh, Perl, C#, CL, DCL, SQL, Tcl, Tk,[3] Chef, Puppet

PowerShell includes its own extensive, console-based help (similar to man pages in Unix shells) accessible via the Get-Help cmdlet. Updated local help contents can be retrieved from the Internet via the Update-Help cmdlet. Alternatively, help from the web can be acquired on a case-by-case basis via the -online switch to Get-Help.

В windows server 2016 должна быть включена транскрипция power shell
The first version of PowerShell
В windows server 2016 должна быть включена транскрипция power shell
PowerShell for Linux 7.3.1 on Ubuntu 22.10

  • cmdlets (.NET Framework programs designed to interact with PowerShell)
  • PowerShell scripts (files suffixed by .ps1)
  • PowerShell functions
  • Standalone executable programs

Extended Type System

The number of cmdlets included in the base PowerShell install has generally increased with each version:

VersionCmdletsRef
Windows PowerShell 1.0[38]
Windows PowerShell 2.0[39]
Windows PowerShell 3.0[40]
Windows PowerShell 4.0?
Windows PowerShell 5.0[41]
Windows PowerShell 5.1[]
PowerShell Core 6.0?
PowerShell Core 6.1?
PowerShell Core 6.2?
PowerShell 7.0[]
PowerShell 7.1?
PowerShell 7.2?
PowerShell 7.4

 
 # Definition of static parameters # Definition of dynamic parameters # Set of instruction to run at the start of the pipeline # Main instruction sets, ran for each item in the pipeline # Set of instruction to run at the end of the pipeline 
 

Desired State Configuration

Upon running a configuration, DSC will ensure that the system gets the state described in the configuration. DSC configurations are idempotent. The Local Configuration Manager (LCM) periodically polls the system using the control flow described by resources (imperative pieces of DSC) to make sure that the state of a configuration is maintained.

Initially using the code name “Monad”, PowerShell was first shown publicly at the Professional Developers Conference in October 2003 in Los Angeles. All major releases are still supported, and each major release has featured backwards compatibility with preceding versions.

Windows PowerShell 1.0

В windows server 2016 должна быть включена транскрипция power shell
Windows PowerShell 1.0 session using the Windows Console

Windows PowerShell 2.0

В windows server 2016 должна быть включена транскрипция power shell
Windows PowerShell ISE v2.0 on Windows 7, an integrated development environment for PowerShell scripts

Windows PowerShell 3.0

  • Scheduled jobs: Jobs can be scheduled to run on a preset time and date using the Windows Task Scheduler infrastructure.
  • Session connectivity: Sessions can be disconnected and reconnected. Remote sessions have become more tolerant of temporary network failures.
  • Improved code writing: Code completion (IntelliSense) and snippets are added. PowerShell ISE allows users to use dialog boxes to fill in parameters for PowerShell cmdlets.
  • Delegation support: Administrative tasks can be delegated to users who do not have permissions for that type of task, without granting them perpetual additional permissions.
  • Help update: Help documentations can be updated via Update-Help command.
  • Automatic module detection: Modules are loaded implicitly whenever a command from that module is invoked. Code completion works for unloaded modules as well.
  • New commands: Dozens of new modules were added, including functionality to manage disks get-WmiObject win32_logicaldisk, volumes, firewalls, network connections, and printers, which had previously been performed via WMI.[further explanation needed]

Windows PowerShell 4.0

New features in PowerShell 4.0 include:

  • Desired State Configuration:[83][84][85] Declarative language extensions and tools that enable the deployment and management of configuration data for systems using the DMTF management standards and WS-Management Protocol
  • New default execution policy: On Windows Servers, the default execution policy is now RemoteSigned.
  • Save-Help: Help can now be saved for modules that are installed on remote computers.
  • Enhanced debugging: The debugger now supports debugging workflows, remote script execution and preserving debugging sessions across PowerShell session reconnections.
  • -PipelineVariable switch: A new ubiquitous parameter to expose the current pipeline object as a variable for programming purposes
  • Network diagnostics to manage physical and Hyper-V‘s virtualized network switches
  • Where and ForEach method syntax provides an alternate method of filtering and iterating over objects.

Windows PowerShell 5.0

В windows server 2016 должна быть включена транскрипция power shell
PowerShell 5.0 icon

Key features included:

  • The new class keyword that creates classes for object-oriented programming
  • The new enum keyword that creates enums
  • OneGet cmdlets to support the Chocolatey package manager[87]
  • Extending support for switch management to layer 2 network switches.[88]
  • Debugging for PowerShell background jobs and instances of PowerShell hosted in other processes (each of which is called a “runspace”)
  • Desired State Configuration (DSC) Local Configuration Manager (LCM) version 2.0
  • DSC partial configurations
  • DSC Local Configuration Manager meta-configurations
  • Authoring of DSC resources using PowerShell classes

Windows PowerShell 5.1

PowerShell Core 6

  • The -Parallel switch for the ForEach-Object cmdlet to help handle parallel processing
  • Near parity with Windows PowerShell in terms of compatibility with built-in Windows modules
  • A new error view
  • The Get-Error cmdlet
  • Pipeline chaining operators (&& and ||) that allow conditional execution of the next cmdlet in the pipeline
  • The ?: operator for ternary operation
  • The ?? operator for null coalescing
  • The ??= operator for null coalescing assignment
  • Cross-platform Invoke-DscResource (experimental)
  • Return of the Out-GridView cmdlet
  • Return of the -ShowWindow switch for the Get-Help

Comparison of cmdlets with similar commands

  1. ls and man aliases are absent in the Linux version of PowerShell Core.
  2. Clear-Host is implemented as a predefined PowerShell function.
  3. Available in Windows NT 4, Windows 98 Resource Kit, Windows 2000 Support Tools
  4. Introduced in Windows XP Professional Edition
  5. Also used in UNIX to send a process any signal, the “Terminate” signal is merely the default
  6. curl and wget aliases are absent from PowerShell Core, so as to not interfere with invoking similarly named native commands.
ExtensionDescription
.ps1Script file[111]
.psd1Module’s manifest file; usually comes with a script module or binary module[112]
.psm1Script module file[113]
.dllDLL-compliant[a] binary module file[114]
.ps1xmlFormat and type definitions file[49][115]
.xmlXML-compliant[b] serialized data file[116]
.psc1Console file[117]
.psscSession configuration file[118]
.psrcRole Capability file[119]
ApplicationVersionCmdletsProviderManagement GUI
Exchange Server2007402YesYes
Windows Server2008YesYesNo
Microsoft SQL Server2008YesYesNo
Microsoft SharePoint2010YesYesNo
System Center Configuration Manager2012 R2400+YesNo
System Center Operations Manager200774YesNo
System Center Virtual Machine Manager2007YesYesYes
System Center Data Protection Manager2007YesNoNo
Windows Compute Cluster Server2007YesYesNo
Microsoft Transporter Suite for Lotus Domino[120]08.02.001247NoNo
Microsoft PowerTools for Open XML[121]1.033NoNo
IBM WebSphere MQ[122]6.0.2.244NoNo
IoT Core Add-ons[123]74Un­knownUn­known
Quest Management Shell for Active Directory[124]1.795NoNo
Special Operations Software Specops Command[125]1.0YesNoYes
VMware vSphere PowerCLI[126]6.5 R1500+YesYes
Internet Information Services[127]7.054YesNo
Windows 7 Troubleshooting Center[128]6.1YesNoYes
Microsoft Deployment Toolkit[129]2010YesYesYes
NetApp PowerShell Toolkit[130][131]4.22000+YesYes
JAMS Scheduler – Job Access & Management System[132]5.052YesYes
UIAutomation[133]0.8432NoNo
Dell Equallogic[134]3.555NoNo
LOGINventory[135]5.8YesYesYes
SePSX[136]0.4.139NoNo
:/>  Ошибка при запуске приложения 0xc0000142, причины

В windows server 2016 должна быть включена транскрипция power shell

Wikiversity has learning resources about PowerShell

  • PowerShell on GitHub
  • Windows PowerShell Survival Guide on TechNet Wiki
PowerShell

Windows PowerShell 5.1, the version that’s built into Windows, shipped back in 2016 with the release of Windows 10 1607 and Windows Server 2016, with support for older OSes back to Windows 7 and Windows Server 2008. That was almost eight years ago. What has changed with PowerShell 5.1 since then? While there are more PowerShell modules and scripts available, the PowerShell 5.1 engine itself is pretty much stuck in time, with no significant changes in those eight years. That doesn’t mean PowerShell itself hasn’t continued to advance, with a number of releases of the new .NET Core-based, cross-platform PowerShell adding lots of improvements, all the way up to today’s PowerShell 7.4 release.

But even with those improvements, there’s still a lot of places where using anything beyond PowerShell 5.1 is harder than it should be. Examples:

  • Intune platform scripts, which only support PowerShell 5.1.
  • Intune remediation scripts, which also only support PowerShell 5.1.
  • Intune app requirement scripts, which only support PowerShell 5.1.
  • ConfigMgr scripts (in the software library, which can be deployed to computers or collections), which only support PowerShell 5.1.
  • ConfigMgr app detection scripts, which only support PowerShell 5.1.
  • Group policy scripts for logon, logoff, startup, and shutdown, which only support PowerShell 5.1.
  • ConfigMgr OS deployment “Run PowerShell script” steps, which only support PowerShell 5.1.
  • MDT “Run PowerShell script” steps, which only support PowerShell 5.1.

See the theme there? So why do these only support PowerShell 5.1 and not the newer releases? There are likely a few reasons:

  1. IT people aren’t asking for support for later versions of PowerShell, because they aren’t familiar with the later versions, because the products don’t support later versions.
  2. Later versions of PowerShell are not (and likely will never be, due to support lifecycle misalignments) preinstalled in Windows, which means there’s a bootstrapping problem: you need to get the later version installed before you can use it.

So how do we solve those issues? A good first step would be to work around the product limitations so that you can use PowerShell 7 directly, and maybe at some point in the future Microsoft will add support for this other Microsoft technology (radical though, I know).

We’re somewhat used to these workarounds, as we’ve been forced to do things like this over the years, e.g. to run 64-bit PowerShell scripts from 32-bit agents. That required small modifications to PowerShell scripts to re-launch themselves in a proper 64-bit process, e.g.:

if ($ENV:PROCESSOR_ARCHITEW6432 -eq "AMD64") { &"$ENV:WINDIR\SysNative\WindowsPowershell\v1.0\PowerShell.exe" -File $PSCOMMANDPATH exit $LASTEXITCODE
}
Write-Host "Hello world"

How would we do the same thing for PowerShell 7? Well, we can certainly re-launch a running script using “pwsh.exe”, but that only solves half of the problem if PowerShell 7 isn’t already installed. Sure, there are some scenarios where you could just deploy the PowerShell 7 installation MSI in advance of trying to use it, but that doesn’t always work — you might not be able to get PowerShell 7 installed in time for the script to use it. The easiest solution for that is to just have the script itself install PowerShell 7, then it can re-launch itself using the newly-installed PowerShell 7 version.

I tried a variety of mechanisms for installing PowerShell 7 and ran into a variety of issues (especially around WinGet, OOBE, and Autopilot), so I ended up abandoning that approach and switching to a super-simple way provided by the PowerShell team:

Invoke-Expression "& { $(Invoke-RestMethod https://aka.ms/install-powershell.ps1) } -UseMSI"

What does that do? It downloads and runs a script (install-powershell.ps1) that itself downloads and runs the latest PowerShell 7 MSI. Perfect, one line to get PowerShell 7 installed. (Notice that there is no separate install of .NET 8, which PowerShell 7 uses. That’s because PowerShell 7 installs with its own copy of .NET 8, contained in the same install folder as the PowerShell 7 files.) But we don’t need to do that if a sufficient PowerShell 7 version is already installed, so it’s useful to add some logic to check on that:

# Check the current installed PowerShell version
if (Test-Path "HKLM:\Software\Microsoft\PowerShellCore\InstalledVersions") { $version = Get-ChildItem "HKLM:\Software\Microsoft\PowerShellCore\InstalledVersions" | Get-ItemPropertyValue -Name SemanticVersion | Measure-Object -Maximum $currentVersion = $version.Maximum Write-Host "Current PowerShell version = $currentVersion"
} else { Write-Host "No PowerShell LTS version found." $currentVersion = "0.0.0"
}

Then there’s another potential challenge: The newly installed version of PowerShell 7 may not be in the path (the system path would be modified, but there’s no guarantee that new processes can see that change until after a reboot). We could fix that by using an explicit path (C:\Program Files\PowerShell\7\pwsh.exe), or we could just manually pull the latest path value — either way works.

And finally, we can re-execute the script using the same sort of logic that was used for 64-bit from 32-bit:

 Try { & pwsh.exe -File $Script } Catch { Throw "Failed to start $PSCOMMANDPATH" } 
# Relaunch as PowerShell 7 if necessary
if ($PSVersionTable.PSVersion.Major -ne 7) { Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted Install-Script PS7Bootstrap -Force -ErrorAction Ignore PS7Bootstrap.ps1 $PSCommandPath Exit $LASTEXITCODE
}

That logic checks to see if the script is already running in PowerShell 7, and if not, it installs the PS7Bootstrap.ps1 script from the PowerShell gallery and then runs it, passing along the full path name of the current script so that it can re-execute the script using PowerShell 7. (If you need to handle parameter passing, you could leave off the $PSCommandPath variable and then run “pwsh.exe -ExecutionPolicy bypass -File $PSCommandPath” yourself, adding additional parameters to the command line.)

The complete SimpleRename7.ps1 script is below:

# Bail out if we aren't in OOBE
$TypeDef = @"
using System;
using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Api
{ public class Kernel32 { [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern int OOBEComplete(ref int bIsOOBEComplete); }
}
"@
Add-Type -TypeDefinition $TypeDef -Language CSharp
$IsOOBEComplete = $false
$hr = [Api.Kernel32]::OOBEComplete([ref] $IsOOBEComplete)
if ($IsOOBEComplete) { Write-Host "Not in OOBE, nothing to do." exit 0
}
# Relaunch as PowerShell 7 if necessary
if ($PSVersionTable.PSVersion.Major -ne 7) { Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force Set-PSRepository -Name "PSGallery" -InstallationPolicy Trusted Install-Script PS7Bootstrap -Force -ErrorAction Ignore PS7Bootstrap.ps1 $PSCommandPath Exit $LASTEXITCODE
}
# Get device information
$systemEnclosure = Get-CimInstance -ClassName Win32_SystemEnclosure
$details = Get-ComputerInfo
# Get the new computer name: use the asset tag (maximum of 13 characters), or the
# serial number if no asset tag is available (replace this logic if you want)
if (($null -eq $systemEnclosure.SMBIOSAssetTag) -or ($systemEnclosure.SMBIOSAssetTag -eq "")) { $assetTag = $details.BiosSerialNumber
} else { $assetTag = $systemEnclosure.SMBIOSAssetTag
}
if ($assetTag.Length -gt 13) { $assetTag = $assetTag.Substring(0, 13)
}
if ($details.CsPCSystemTypeEx -eq 1) { $newName = "D-$assetTag"
} else { $newName = "L-$assetTag"
}
# Is the computer name already set? If so, bail out
if ($newName -ieq $details.CsName) { Write-Host "No need to rename computer, name is already set to $newName" Exit 0
}
# Set the computer name
Write-Host "Renaming computer to $($newName)"
Rename-Computer -NewName $newName -Force

We can specify that in Intune as a platform script:

:/>  Сколько занимает Windows 7 и сколько места Windows 7 занимает на компьютере?
В windows server 2016 должна быть включена транскрипция power shell

When it runs, it will initially be running in PowerShell 5.1. Since this is designed to run on a brand-new OS install, during OOBE, it will install PowerShell 7 on the device and then re-execute itself in PowerShell 7 to rename the computer.

The same basic approach works for most of the other cases mentioned above (Intune, SCCM, Group Policy, MDT): let your script start in PowerShell 5.1, then relaunch in PowerShell 7. The OS deployment / task sequence steps that would run in Windows PE would be more challenging — that’s a topic for a future date. But steps that run in the new/full OS could either leverage this approach, or just have an initial step that installs the PowerShell 7 MSI so that later “Run command line” steps can use it directly.


Discover more from Out of Office Hours

Установка модуля управления обновлениями 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. Чтобы разрешить запуск любых локальных скриптов, выполните команду:

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

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

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

Поиск (сканирование) доступных обновлений 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 скачать доступные обновления на диск

Установка обновлений 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 после установки обновлений

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

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

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

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

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

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

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

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

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

Remove-WindowsUpdate -KBArticleID KB4011634

Скрыть ненужные обновления 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 на удаленных компьютерах через 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 Server 2016 must have PowerShell Transcription enabled.

Overview

Finding IDVersionRule IDIA ControlsSeverity
V-257502WN16-CC-000555SV-257502r921892_ruleMedium
Description
Maintaining an audit trail of system activity logs can help identify configuration errors, troubleshoot service disruptions, and analyze compromises that have occurred, as well as detect attacks. Audit logs are necessary to provide a trail of evidence in case the system or network is compromised. Collecting this data is essential for analyzing the security of information assets and detecting signs of suspicious and unexpected behavior.

Enabling PowerShell Transcription will record detailed information from the processing of PowerShell commands and scripts. This can provide additional detail when malware has run on a system.

STIGDate
Microsoft Windows Server 2016 Security Technical Implementation Guide2023-08-22

Details

Check Text ( C-61237r921890_chk )
If the following registry value does not exist or is not configured as specified, this is a finding:

Registry Hive: HKEY_LOCAL_MACHINE
Registry Path: \SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription\

Value Name: EnableTranscripting

Value Type: REG_DWORD
Value: 1

Fix Text (F-61161r921891_fix)
Configure the policy value for Computer Configuration >> Administrative Templates >> Windows Components >> Windows PowerShell >> “Turn on PowerShell Transcription” to “Enabled”.