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:
- 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.
- 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 -ForceWe can specify that in Intune as a platform script:

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
2023-12-14T21:05:44Z [Verbose] Sending invocation id: '3e85a40a-a930-78d8-be83-f53bd9847ab1
2023-12-14T21:05:44Z [Verbose] Posting invocation id:3e85a40a-a930-78d8-be83-f53bd9847ab1 on workerId:e8588e50-b2ad-4012-bf5b-92df7aa00739
2023-12-14T21:05:44Z [Warning] The Function app may be missing the 'Az.Accounts' module. If 'Az.Accounts' is available on the PowerShell Gallery, add a reference to this module to requirements.psd1. Make sure this module is compatible with PowerShell 7. For more details, see [here](https://aka.ms/functions-powershell-managed-dependency).
2023-12-14T21:05:44Z [Error] ERROR: The specified module 'Az.Accounts' was not loaded because no valid module file was found in any module directory.
Exception : Type : System.IO.FileNotFoundException Message : The specified module 'Az.Accounts' was not loaded because no valid module file was found in any module directory. HResult : -2147024894
TargetObject : Az.Accounts
CategoryInfo : ResourceUnavailable: (Az.Accounts:String) [Import-Module], FileNotFoundException
FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
InvocationInfo : MyCommand : Import-Module ScriptLineNumber : 9 OffsetInLine : 1 HistoryId : 1 ScriptName : C:\home\site\wwwroot\Func_Sample_1\run.ps1 Line : Import-Module Az.Accounts -Force PositionMessage : At C:\home\site\wwwroot\Func_Sample_1\run.ps1:9 char:1 + Import-Module Az.Accounts -Force + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PSScriptRoot : C:\home\site\wwwroot\Func_Sample_1 PSCommandPath : C:\home\site\wwwroot\Func_Sample_1\run.ps1 InvocationName : Import-Module CommandOrigin : Internal
ScriptStackTrace : at <ScriptBlock>, C:\home\site\wwwroot\Func_Sample_1\run.ps1: line 9
PipelineIterationInfo :
[... Repeat for 'Az.Resources' and 'SqlServer' ...]Requirements.psd1
# See [here](https://aka.ms/functionsmanageddependency) for additional information.
@{ 'Az.Accounts' = '2.*' 'Az.Resources' = '6.*' 'SqlServer' = '22.*'
}using namespace System.Data.SqlClient
param($Request, $TriggerMetadata)
# Import the necessary modules
Import-Module Az.Accounts -Force
Import-Module Az.Resources -Force
Import-Module SqlServer -Force
# Authenticate to Azure
Connect-AzAccount
Write-Host "Request database access token for managed identity"
$MI_Token = (Get-AzAccessToken -ResourceUrl https://database.windows.net ).TokenVerified that the modules added in requirements.psd1 are available in the PowerShell Gallery. My understanding is that modules should be downloaded automatically if they are available in the PowerShell Gallery. However, it fails in the portal. Tried manually copying the modules into the site wwwroot\Modules folder, but it still didn’t help. Running out of ideas on what’s missing and how to fix it. Any help would be greatly appreciated! Thank you.
В этой статье мы рассмотрим, как массово проверить ваши компьютеры на совместимость с Windows 11 с помощью PowerShell скрипта. За основу можно взять официальный скрипт HardwareReadiness.ps1 от Microsoft (https://aka.ms/HWReadinessScript).
Данный скрипт проверяет, что компьютер удовлетворяет следующим минимальным требованиям, необходимым для запуска Windows 11:
- Совместимый x64 процессор (полный список поддерживаемых CPU)
- 4+ ГБ RAM
- Минимальный размер диска 64 ГБ
- Устройство с UEFI и включенной Secure Boot
- Видеокарта совместимая с DirectX 12 и WDDM 2.0 драйверов
- TPM 2.0 модуль
- Монитор с разрешением 720x
Чтобы вручную проверить совместимость отдельного компьютера с Windows 11,
- Cкачайте скрипт HardwareReadiness.ps1 по ссылке выше.
- Откройте консоль Windows PowerShell с правами администратора (в скрипте используется командлет Get-WMIObject, который не поддерживается в более новой версии PowerShell Core)
- Разрешите запуск PowerShell скрипта в текущей сессии:
Set-ExecutionPolicy -Scope Process RemoteSigned - Выполните скрипт:
.\HardwareReadiness.ps1

Скрипт вернул код 0. Это значит, что компьютер совместим с требованиями Windows 11 (
returncode:0
,
resurnresult=CAPABLE
).
{"returnCode":0,"returnReason":"","logging":"Storage: OSDiskSize=427GB. PASS; Memory: System_Memory=32GB. PASS; TPM: TPMVersion=2.0, 0, 1.38. PASS; Processor: {AddressWidth=64; MaxClockSpeed=3901; NumberOfLogicalCores=12; Manufacturer=AuthenticAMD; Caption=AMD64 Family 25 Model 80 Stepping 0; }. PASS; SecureBoot: Capable. PASS; ","returnResult":"CAPABLE"}Если нужно проверить множество корпоративных компьютеров на совместимость с Windows 11, тогда для распространения этого скрипта и сбора информации можно использовать такие инструменты как SCCM, Intune или даже WSUS для запуска сторонних скриптов. В самом простом случае можно запустить этот PowerShell скрипт с помощью групповых политик и сохранить результаты в свойства компьютера в Active Directory.
Код скрипт нужно немного модифицировать.

Данный код запишет в атрибут компьютера Info в Active Directory информацию о совместимости с Windows 11.
Скопируйте скрипт в папку
\\winitpro.loc\Netlogon
на контроллере домена.

Откройте консоль управления доменными групповыми политиками (
gpmc.msc
) и создайте новую GPO для OU с компьютерами.
Перейдите в раздел Computer Configuration -> Policies -> Windows Settings -> Scripts (Startup / Shutdown) -> Startup -> вкладка PowerShell Scripts и укажите UNC путь к скрипту HardwareReadiness.ps1

Перезагрузите компьютер. Запустите консоль ADUC (
dsa.msc
), и откройте свойства компьютера. Перейдите на вкладку редактора атрибутов и проверьте, что в параметре Info теперь содержится результаты проверки компьютера на совместимость с Windows 11.

После того, как логон скрипт отработает на всех компьютерах, вы можете быстро вывести информацию о совместимых и не совместимых компьютерах из Active Directory с помощью командлета Get-ADComputer.

$Report = @()
$computers = Get-ADComputer -Filter {enabled -eq "true"} -properties *| Where-Object { $_.Info -match '"returnCode":1'}
foreach ($computer in $computers){ $jsonString =$computer.info $object = $jsonString | ConvertFrom-Json $returnReasonValues = $object.returnReason -split ', ' $CompInfo = [PSCustomObject]@{ "Computer" = $computer.name "NonCompatibleItems" = $returnReasonValues } $Report += $CompInfo
}
$Report|flДля преобразования данных из JSON формата используется командлет ConvertFrom-Json.

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

Чтобы обновить вашу версию 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 4.8 (потребуется перезагрузка).

Если установить WMF 5.1, но не установить .NET 4.5.2 (или более новый), часть функций PowerShell не будет работать.
Установите 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 установщика

Доступны следующие опции установки:
- 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, выполните команду:
Данная команда загружает установочный 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
Так можно проверить версию файла на удаленном компьютере:
Чтобы запустить предыдущую версию 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 установлен.

Но есть и недостатки, связанные с тем, что такой 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.



