Обновление версии power shell в windows

Windows PowerShell is installed on Windows systems by default. But that’s Windows PowerShell and not PowerShell. To make the most out of PowerShell, you should upgrade to PowerShell 7. In this article, you will learn how to install and update PowerShell 7.

How to update Powershell

To take full advantage of its capabilities and ensure access to the latest features and cmdlets in scripts, it’s important to keep PowerShell updated. In this comprehensive guide, we’ll cover various methods to update PowerShell to the latest version and how to install or upgrade to PowerShell 7. Let’s get started!

With the advent of Windows 11, enabling its upgrade became a primary focus for IT professionals. Understanding and managing operating system transitions is crucial in the IT sector, especially as businesses work to remain compatible with the latest technologies. The script in focus offers a streamlined way to pave the way for the Windows 11 upgrade.

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

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.  

Important Things Before You Update PowerShell

Before you upgrade PowerShell version, it’s necessary to know some basic information related to this subject. Here we summarize the most frequently asked questions.

What Is the Latest PowerShell Version

Since its release, Windows PowerShell has experienced several versions, including PowerShell 1.0, PowerShell 2.0, PowerShell 3.0, PowerShell 4.0, PowerShell 5.0, PowerShell 5.1, PowerShell Core 6, PowerShell 7, and PowerShell 7.2. According to the official information from Microsoft, the latest version of PowerShell is upgraded to V7.2.5 on June 21, 2022. Well, the PowerShell Preview v7.3.0 was also released in 2022.

So, what’s the latest PowerShell version for Windows 10/11? PowerShell 7.2 is the latest current version for Windows 10/11. To give you an intuitive understanding, here we summarize the most commonly used PowerShell versions that support different Windows OS:

supported Windows 0S for different PowerShell versions

What Version of PowerShell Do I Have

Step 1. Right-click the Windows Start menu at the bottom of your left screen and select Windows PowerShell.

Step 3. Scroll down to the PSVersion section and the value next to it is the current PowerShell version of your computer. As the picture shows below, the current PowerShell version is 5.1.

check PowerShell version on Windows 10

Understanding the Different Versions of PowerShell

Before we dive into updating PowerShell, it’s important to understand that there are two distinct versions of PowerShell:

  1. Windows PowerShell: This is the classic version of PowerShell, with the latest and final version being 5.1. Microsoft is no longer actively updating Windows PowerShell because they have shifted their focus to PowerShell Core.
  2. PowerShell Core: This is the new, open-source, cross-platform version of PowerShell, with the current version being 7.3. PowerShell Core is built on .NET Core and is designed to be compatible with most Windows PowerShell scripts and cmdlets.

While the version numbering for PowerShell Core continues from 5.1 (6.0, 6.1, 7.0, 7.1, etc.), the two platforms are distinct and require separate update processes.

Checking Your Current PowerShell Version

  1. Open Windows PowerShell.
  2. Type the following command and press Enter:
$PSVersionTable.PSVersion

This command will display your current PowerShell version in the console. 

Get PowerShell Version

Why should we update to PowerShell 7?

There are numerous reasons to consider updating to PowerShell 7, as it offers significant enhancements to its predecessors. Here are some compelling reasons to upgrade:

  1. Cross-platform compatibility: PowerShell 7 is built on .NET Core, which allows it to run on Windows, macOS, and Linux. This enables you to use the same PowerShell scripts and modules across different operating systems, streamlining your workflows and making your automation efforts more efficient.
  2. Improved performance: PowerShell 7 boasts enhanced performance, thanks to the underlying .NET Core runtime. This means faster script execution, reduced memory usage, and better overall performance, allowing you to accomplish your tasks more efficiently.
  3. New features and improvements: PowerShell 7 introduces a wealth of new features, cmdlets, and improvements, such as enhanced PowerShell remoting, improved error messages, and support for ternary operators. These enhancements make PowerShell 7 more powerful, versatile, and user-friendly.
  4. Long-term support: PowerShell 7 is a long-term support (LTS) release, meaning it will receive updates and bug fixes for an extended period. This ensures that your PowerShell environment remains stable, secure, and up-to-date.
  5. Compatibility with Windows PowerShell: PowerShell 7 offers a high level of compatibility with Windows PowerShell, allowing you to continue using your existing scripts and modules with minimal modifications. This makes the transition to PowerShell 7 smoother and less disruptive.
  6. Enhanced security: PowerShell 7 includes several security improvements, such as the new -NoLogo switch, which prevents the display of potentially sensitive information in the PowerShell console, and improved logging capabilities, which help you monitor and audit your PowerShell activities.
  7. Pipeline parallelization: PowerShell 7 introduces the ForEach-Object -Parallel cmdlet, which enables parallel execution of script blocks across multiple cores and threads. This can significantly improve the performance of scripts that process large amounts of data.
  8. Additional cmdlets and modules: PowerShell 7 includes several new cmdlets and modules, such as the ConvertFrom-Json and ConvertTo-Json cmdlets for working with JSON data, and the Microsoft.PowerShell.GraphicalTools module for building graphical user interfaces (GUIs). PowerShell 7 includes improved error messages.

Обновление 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.

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

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

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

Windows PowerShell vs PowerShell

There are two PowerShell versions that you need to be aware of:

  • Windows PowerShell (version 1.0 – 5.1)
    It’s preinstalled on all modern Windows client and server OS releases. It’s not being developed further, and the latest version is 5.1. The executable is powershell.exe.
  • PowerShell (version 6 and higher)
    It’s not preinstalled on any version of Windows. It’s actively being developed, is much faster, and has better commands available. The executable is pwsh.exe.

Note: You can have both Windows PowerShell and PowerShell versions installed next to each other on the same system.

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.

  1. Download the PowerShell MSI installation file and copy it to the SYSVOL directory on the domain controller;
  2. Open the Domain Group Policy Management Console (gpmc.msc), create a new GPO and link it to the OU with computers and servers;
  3. 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); updating powershell on domain computers using gpo

    To more accurately target your policy to domain devices, you can use the GPO WMI filters.

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

Prerequisites for upgrading to PowerShell 7

  1. Supported operating systems: Ensure that you are running a compatible operating system. PowerShell 7 supports Windows 7, 8.1, 10, and 11; macOS 10.13 and later; and various Linux distributions, including Ubuntu, Debian, CentOS, Fedora, and more.
  2. .NET Core 3.1: PowerShell 7 requires .NET Core 3.1 to be installed on your system. You can download the latest version of .NET Core from the Official website.
  3. Backup your existing PowerShell configuration: Before upgrading, it is recommended to back up your existing PowerShell configuration, including profiles, scripts, and modules, to ensure a smooth transition and minimize the risk of data loss.

Implications

While the script offers a way to enable the Windows 11 upgrade seamlessly, any automated process comes with risks. Altering registry settings can have unintended consequences. IT professionals must ensure they have backup strategies in place, test the script in controlled environments, and always prioritize IT security.

:/>  Sign in failed перевод

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

console notification: A new PowerShell stable release is available

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.

enable the option: receive updates for other microsoft products via windows update

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.

windows check for powershell updates

Potential Use Cases

Imagine an IT professional, George, working for a medium-sized enterprise. The company decides to transition to Windows 11 to leverage its new features. George, tasked with ensuring a smooth transition, utilizes this script to batch-enable the upgrade across all systems, saving significant manual work.

Upgrading PowerShell on other platforms (Mac, Linux)

PowerShell 7 can also be installed on macOS and Linux. The installation process for these platforms is similar to Windows, with some platform-specific differences:

  1. macOS: Download the PowerShell 7 PKG installer from the PowerShell GitHub repository and run it. Follow the on-screen prompts to complete the installation. Verify the installation by opening a new terminal and typing pwsh. You can also use Homebrew by running brew install --cask powershell.
  2. Linux: Installation on Linux varies depending on your distribution. Follow the official documentation for detailed instructions on installing PowerShell 7 on your specific Linux distribution. For example, on Ubuntu or Debian, you can use the following commands: sudo apt-get update and sudo apt-get install -y powershell

Alternative Approach

Traditional methods of enabling Windows 11 upgrades might involve manual changes in system settings or using GUI-based tools which are time-consuming and prone to errors. This script automates the process, making it more efficient and error-resistant.

Find PowerShell version

Note: Windows PowerShell and PowerShell are different versions and you need to start the correct PowerShell window and run the command below.

$PSVersionTable.PSVersion

This is how it looks if you run it in Windows PowerShell.

Major Minor Build Revision
----- ----- ----- --------
5 1 20348 1

See the screenshot below.

Install and Update PowerShell 7 check version Windows PowerShell

This is how it looks if you run it in PowerShell.

Major Minor Patch PreReleaseLabel BuildLabel
----- ----- ----- --------------- ----------
7 4 0

See the screenshot below.

Install and Update PowerShell 7 check version PowerShell

Method 1: One-liner

This is the fastest and easiest method to install PowerShell 7.

iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI"

After that, you see the PowerShell 7 setup wizard that you can go through.

Install and Update PowerShell 7 setup

Ensure you enable all options.

Обновление версии power shell в windows

Since PowerShell 7.2 and higher, Microsoft will automatically update PowerShell 7 in the same release channel if you enable it in the setup wizard. For example, PowerShell 7.2.x to 7.2.y and 7.3.x to 7.3.y.

Enable both options.

Install and Update PowerShell 7 Microsoft Update

Finish the installation.

Обновление версии power shell в windows

PowerShell 7 appears in your programs.

Обновление версии power shell в windows

Method 2. Download from GitHub

Go to the PowerShell GitHub page and download the PowerShell 7 installer.

Install and Update PowerShell 7 GitHub

Open the PowerShell .msi file and go through the setup wizard, as shown in the above method.

Method 3: WinGet (Windows Package Manager)

Run the below command to download and install PowerShell 7.

Note: It will automatically install PowerShell 7 once downloaded, and you will not see the setup wizard.

winget install --id Microsoft.Powershell

Update PowerShell 7

It’s best to update PowerShell 7 every time a new version is out.

Use the winget upgrade command to update PowerShell 7 to the latest version.

winget upgrade --id Microsoft.PowerShell

The other methods to upgrade PowerShell 7 are to download the installer from GitHub or run the one-liner as shown above, which then you can go through the setup wizard to update PowerShell.

How to update PowerShell on Windows 10/11?

There are several methods to install or update PowerShell Core 7 on your Windows system:

Method 1: Using Winget Command

  1. Open a PowerShell terminal window with administrative privileges.
  2. To search for the available PowerShell versions, run the following command:
winget search Microsoft.Powershell
  1. To install the desired PowerShell Core version, use the following command:
winget install --id Microsoft.PowerShell

This will download and install the latest stable PowerShell Core release. Similarly, If you want to update your existing PowerShell 7 version to the latest build, You use:

winget upgrade --id Microsoft.PowerShell
update powershell 7

Method 2: Using GitHub to Download PowerShell 7 Installer

  1. Visit the GitHub PowerShell page and select the latest release version.
    Download PowerShell from GitHub
  2. Scroll to the Assets section and download the appropriate MSI package or zip package for your operating system.
  3. Run the installer package and follow the installation wizard to complete the process. During installation, you can enable WSUS or Windows update to update PowerShell.
    Install PowerShell 7

How to Update PowerShell 7 to the Latest Build?

If you have installed PowerShell 7 with an MSI, You can upgrade to the latest build by downloading and installing the latest MSI from the GitHub PowerShell page to update PowerShell 7.

Method 3: Using Microsoft Store

  1. Open the Microsoft Store app on your PC.
  2. Search for the “PowerShell” app.
    Install PowerShell 7 from Microsoft Store
  3. Click the Get or Update button to download and install the app on your system.

Launch PowerShell 7

After the installation, To access PowerShell 7, open the Start Menu, search for “PowerShell 7,” and select the PowerShell 7 option.

Access PowerShell 7

Please note that you can’t use PowerShell ISE with PowerShell 7 yet! So, use Visual Studio Code.

Verify the PowerShell 7 Version:

Open a new PowerShell console and type Get-Host. The “Version” property should display “7.x.x” (where “x” represents the version number). Ensure your existing scripts and modules work correctly in PowerShell 7. If you encounter any issues, refer to the PowerShell 7 migration guide for assistance.

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 powershell core msi installer from github

Download the MSI file and install it.

  • 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

install powershell core on windows

Next, you can enable automatic updates of the PowerShell Core through Windows Update/WSUS (see below).

enable powershell core update via microsoft update

  • 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

This command downloads the PowerShell 7.3 MSI file from GitHub and then starts the installation via the MSI installer.

upgrade powershell core 7.1 from command line

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.

powershell core updated to 7.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\6directory 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

pwsh.exe - powershell core executable

This means that you have both Windows PowerShell 5.1 and PowerShell Core 7.3 installed on your computer.

two powershell version on windows 10

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

get pwsh.exe file version

This is how you can check the version of a file on a remote computer:

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.

:/>  Как проверить номер материнской платы на ПК с Windows

To verify that you have installed the Store version of PowerShell Core, use the command:

The Microsoft.PowerShell_7.3.3.0_x64__8wekyb3d8bbwe package is installed in this example.

appx-package of powershell core from microsoft store

However, there are also drawbacks to the fact that such an instance of PowerShell will be running in a sandbox environment.

install powershell on windows via 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 versions and release date

PowerShell has gone a long way since its first release. See the table below for all the PowerShell versions and their release date.

PowerShell versionRelease date
PowerShell 7.4November 2023
PowerShell 7.3November 2022
PowerShell 7.2November 2021
PowerShell 7.1November 2020
PowerShell 7March 2020
PowerShell 6.2March 2019
PowerShell 6.1September 2018
PowerShell 6.0January 2018
Windows PowerShell 5.1August 2016
Windows PowerShell 5.0February 2015
Windows PowerShell 4.0October 2013
Windows PowerShell 3.0October 2012
Windows PowerShell 2.0July 2009
Windows PowerShell 1.0November 2006

Script Detailed Breakdown

Preparation Phase

The script starts with a CmdletBinding attribute, commonly used for advanced functions in PowerShell. It doesn’t require any parameters.

Execution Phase

The script defines a variable $Splat which holds information related to the Windows Update registry path and some properties.

Finally, the script checks whether these registry properties were successfully removed. If they were not, it signals a failure in enabling the upgrade.

Completion Phase

The script exits with a status code. A zero (0) indicates successful completion, while one (1) signifies an error.

Frequently Asked Questions (FAQ)

How to uninstall Windows PowerShell 5.1 on Windows after installing PowerShell 7?

You don’t. It’s integrated with Windows OS, and you must leave it on your system.

Why does Windows PowerShell ISE show version 5.1 when I have PowerShell 7 installed?

PowerShell ISE loads Windows PowerShell 5.1 and not PowerShell 7.

How can I keep using Windows PowerShell ISE with PowerShell 7?

Switch over to Visual Studio Code. It’s a free, lightweight, open-source, cross-platform code editor.

Will PowerShell 7 load automatically in Visual Studio Code?

PowerShell 7 takes precedence over Windows PowerShell 5.1 and loads by default.

Can I switch between Windows PowerShell 5.1 and PowerShell 7 in Visual Studio Code?

Select a default profile and choose Windows PowerShell 5.1 or PowerShell 7.

Why doesn’t Microsoft ship PowerShell 7 with Windows?

Microsoft plans to eventually ship PowerShell 7 in Windows as a side-by-side feature with Windows PowerShell 5.1. But they still need to work out some details, and there is no timeline for when that will happen.

Should I use Windows PowerShell 5.1 or PowerShell 7?

You should definitely use PowerShell 7 when you can. But ensure you test all your cmdlets and scripts before transitioning to PowerShell 7.

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

Updating from PowerShell 3, 4 to PowerShell 5.1

PowerShell 5.1 is installed on Windows systems by default and is part of the Windows Management Framework 5.1 (which requires the .NET Framework 4.5.2 or later). It automatically updates with Microsoft Update, so ensure your system is up to date to have the latest version of PowerShell 5.1. If you are using an older version of PowerShell (such as PowerShell 3 or 4 on Windows Server 2012 R2, 2012, 2008 R2 SP1, Windows 8.1, and Windows 7 SP1), you can update to PowerShell 5.1 by installing the Windows Management Framework 5.1

Common issues and troubleshooting during the upgrade process

  1. Installation errors: If you encounter errors during the installation process, ensure that you have met all the prerequisites, such as installing .NET Core 3.1, and that you are using the correct installer for your system.
  2. Compatibility issues: If your existing scripts and modules do not work correctly in PowerShell 7, refer to the PowerShell 7 migration guide for guidance on updating your code.
  3. Performance issues: If you experience performance issues, such as slow script execution or high memory usage, ensure you are using the latest version of PowerShell 7 and .NET Core, and consider optimizing your scripts for parallel execution.
  4. Security issues: If you encounter security issues, such as unauthorized access or data breaches, review your PowerShell security settings and ensure that you are following best practices for secure scripting.

In most cases, updating PowerShell should not affect your existing scripts. However, it’s always a good practice to test your scripts with the new version of PowerShell to ensure compatibility before deploying them in a production environment.

Table of contents

  • Understanding the Different Versions of PowerShell
  • Updating from PowerShell 3, 4 to PowerShell 5.1
  • Introduction to PowerShell 7
  • Why should we update to PowerShell 7?
  • Prerequisites for upgrading to PowerShell 7
  • Step-by-step guide: How to update PowerShell on Windows 10/11?
  • Common issues and troubleshooting during the upgrade process
  • Conclusion and next steps in your PowerShell journey

Обновление Windows PowerShell до 5.1

Во всех версиях, начиная с Windows 10 и Windows Server 2016, Windows PowerShell 5.1 уже установлен по-умолчанию.

:/>  Как включить открытие одним кликом в windows 10

В предыдущих версиях (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).

Table of contents

  • Windows PowerShell vs PowerShell
  • PowerShell versions and release date
  • Find PowerShell version
  • Install PowerShell 7
  • Update PowerShell 7
  • Frequently Asked Questions (FAQ)
  • Conclusion

How to Update PowerShell to the Latest Version for Windows 10/11

Way 1. Update PowerShell Version Via MSI Package

If you don’t know if your system is x86 or x64 version, read this post.

install the MSI package

Step 2. Once downloaded, double click the PowerShell-7.2.5 msi installer file and click on Next.

click Next in PowerShell 7 setup wizard

Step 3. Select a destination folder for the PowerShell v7.2.5 package and click on Next. If you haven’t changed the location, the default path of the package is installed to C:ProgramFilesPowerShellversion

select Destination folder for PowerShell installation

Step 4. Select the Optional Actions and click on Next. Here you can customize the installation for PowerShell.

select Optional Actions for PowerShell installation

Step 5. PowerShell 7.2 version comes with automatic updates through the Microsoft Update service. Here you can tick the checkbox next to Enable updating PowerShell through Microsoft Update or WSUS (recommended) and click on Next.

Enable updating PowerShell through Microsoft Update or WSUS

Step 6. Click on Install and then on Yes in the UAC window to start installing the latest PowerShell version 7.2.5.

=installing PowerShell 7 in Windows 10

Step 7. Once installed, you can click on Finish or launch the latest PowerShell version 7.2.5 later.

=click Finish on PowerShell 7 installation wizard

Step 8. If you want to start the latest PowerShell version, type powershell in the Search box and select PowerShell 7 (x64). Then you can run the $PSversionTable command and check if the PowerShell version is v7.2.5.

=run PowerShell 7

Way 2. Update PowerShell Version Via Microsoft Store

Another simple way about how to upgrade PowerShell is to use Microsoft Store. Now, the latest PowerShell version 7.2.5 can be installed from the Store. Here’s how to install it.

Step 1. Open Microsoft Store on your computer, and then type powershell in the search box and select PowerShell from the listed results.

Step 2. Once the latest PowerShell version package appears, click on Get and wait for the installation to complete.

=download PowerShell from Microsoft Store

Step 3. Once installed, click on Open and the PowerShell 7.2.5 x64 pwsh.exe window will be shown as the picture below:

=open PowerShell window via Microsoft Store

What’s the latest PowerShell version for Windows 10/11? How to upgrade PowerShell? Now, I believe that you already have known the answers.

The Script

<#
.SYNOPSIS Enables Windows 11 upgrade.
.DESCRIPTION Enables Windows 11 upgrade.
.EXAMPLE No parameters needed Enables Windows 11 upgrade.
.OUTPUTS None
.NOTES Minimum OS Architecture Supported: Windows 10 Release Notes: Allows the upgrade offer to Windows 11 to appear to users (c) 2023 NinjaOne By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use. Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>
[CmdletBinding()]
param ()
begin { function Test-IsElevated { $id = [System.Security.Principal.WindowsIdentity]::GetCurrent() $p = New-Object System.Security.Principal.WindowsPrincipal($id) $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator) }
}
process { if (-not (Test-IsElevated)) { Write-Error -Message "Access Denied. Please run with Administrator privileges." exit 1 } $Splat = @{ Path = "HKLM:SOFTWAREPoliciesMicrosoftWindowsWindowsUpdate" Name = @("TargetReleaseVersion", "TargetReleaseVersionInfo") ErrorAction = "SilentlyContinue" } Remove-ItemProperty @Splat -Force Remove-ItemProperty -Path "HKLM:SOFTWAREMicrosoftWindowsUpdateUXSettings" -Name "SvOfferDeclined" -Force -ErrorAction SilentlyContinue $TargetResult = Get-ItemProperty @Splat $OfferResult = Get-ItemProperty -Path "HKLM:SOFTWAREMicrosoftWindowsUpdateUXSettings" -Name "SvOfferDeclined" -ErrorAction SilentlyContinue if ($null -ne $TargetResult -or $null -ne $OfferResult) { Write-Host "Failed to enable Windows 11 Upgrade." exit 1 } exit 0
}
end {}

Access 300+ scripts in the NinjaOne Dojo

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 check powershell version

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

get .net framework version on windows

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=2088631ndp48-x86-x64-allos-enu.exe).

Install the .NET 4.8 package (you will need to restart your computer):

installing net framework 4.8 on windows server 2012 r2

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.

install Windows Management Framework 5.1

After you restart the server, open the powershell.exe console and make sure that the PowerShell version has been updated to 5.1.

update to windows powershell 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).

FAQs

  1. Will this script work for OS other than Windows 10?
    The script is primarily designed for Windows 10, as highlighted in the notes.
  2. What if the script doesn’t work?
    It’s essential to run the script with administrative rights. If faced with issues, re-running it or consulting with IT specialists is advisable.

Conclusion and next steps in your PowerShell journey

In this article, we have explored the benefits of updating to PowerShell 7, the prerequisites for upgrading, and detailed step-by-step instructions on how to update PowerShell on various platforms. By upgrading to PowerShell 7, you can take advantage of its cross-platform capabilities, improved performance, and new features and improvements.

Why should I update PowerShell?

Updating PowerShell ensures that you have access to the latest features, bug fixes, and security improvements. Newer versions of PowerShell often include performance enhancements and compatibility with the latest operating systems.

How do I check my current PowerShell version?

Should I use Windows PowerShell 5.1 or PowerShell Core 7?

Windows PowerShell 5.1 is still installed by default on Windows client and server operating systems. However, Microsoft recommends using PowerShell Core 7 whenever possible, as it will receive ongoing development and updates. It is important to test your existing scripts and modules for compatibility with PowerShell Core 7 before fully transitioning.

How do I check the version of PowerShell Core 7 after installation?

After installing PowerShell Core 7, you can check the version by opening a PowerShell Core window and running the $PSVersionTable.PSVersion command.

Can I have both Windows PowerShell and PowerShell Core 7 installed on the same system?

Yes, you can use both versions on your system since PowerShell Core 7 is installed alongside Windows PowerShell. This lets you gradually transition to PowerShell Core 7 while maintaining access to Windows PowerShell for compatibility purposes.

How do I revert to an earlier version of PowerShell if needed?

To revert to an earlier version, uninstall the current version and reinstall the version you wish to return to. For PowerShell Core, simply switch to the earlier version if you have multiple versions installed.

What is the difference between Windows PowerShell and PowerShell Core?

Windows PowerShell is the classic version of PowerShell, while PowerShell Core is the new, open-source, cross-platform version of PowerShell. Microsoft is no longer actively updating Windows PowerShell because they have shifted their focus to PowerShell Core.

Final Thoughts

Transitioning to new OS versions can be daunting. Using tools and scripts like the one discussed can ease the process. Furthermore, an IT management platform like NinjaOne can further assist in managing such transitions, offering monitoring and automation capabilities that are invaluable in today’s rapidly evolving IT landscape.

Conclusion

You learned how to install and update PowerShell 7. Ensure that you use PowerShell 7 when you can because it’s kept up to date by Microsoft and performs much faster than the older versions. If it’s impossible to port some of your commands and scripts to PowerShell 7, then keep using PowerShell 5.1 for those.

Recommendations

  • Always backup critical data and system settings before running scripts.
  • Test the script on a small sample of machines before broad deployment.
  • Ensure users are informed about upgrades to prevent surprises.