В этой статье мы рассмотрим какие версии PowerShell существуют, в чем отличие Windows PowerShell от PowerShell Core и как узнать, какая версия PowerShell установлена на локальном или удаленных компьютерах.
Содержание:
- История версии PowerShell, PowerShell Core
- Как узнать версию PowerShell из консоли?
- Получаем версию PowerShell на удаленных компьютерах
История версии PowerShell, PowerShell Core
По умолчанию PowerShell устанвлен во всех версиях Windows, начиная с Windows 7 SP1 и Windows Server 2008 R2 SP1. В следующей таблице представлен список актуальных версий PowerShell:
Версия PS | Примечание |
PowerShell 1.0 | Можно было установить вручную в Windows Server 2003 SP1 и Windows XP |
PowerShell 2.0 | Предустановлен в Windows Server 2008 R2 и Windows 7 |
PowerShell 3.0 | Установлен в Windows 8 и Windows Server 2012 |
PowerShell 4.0 | Предустановлен в Windows 8.1 и Windows Server 2012 R2 |
PowerShell 5.0 | Предустановлен в Windows 10 RTM, и автоматически обновляется до 5.1 через Windows Update |
PowerShell 5.1 | Встроен в Windows 10 (начиная с билда 1709) и Windows Server 2016 |
PowerShell Core 6.0 и 6.1 | Следующая кроссплатформенная версия PowerShell (основана на .NET Core), которую можно установить не только во всех поддерживаемых версиях Windows, но и в MacOS, CentOS, RHEL, Debian, Ubuntu, openSUSE |
PowerShell Core 7.0 | Самая последняя версия PowerShell, вышедшая в марте 2020 (в новом релизе выполнен переход с .NET Core 2.x на 3.1) |
Вы можете вручную установить более новую версию PowerShell в предыдущих версиях Windows. Для этого нужно скачать и установить соответствующую версию Windows Management Framework (PowerShell входит в его состав).
Стоит обратить внимание, что последние 2 года Microsoft приостановила развитие классического Windows PowerShell (выпускаются только исправления ошибок и безопасности) и сфокусировалась на открытом кроссплатформенном PowerShell Core. В чем отличия Windows PowerShell от PowerShell Core?
- Windows PowerShell основан на NET Framework (например, для PowerShell 5 требуется .NET Framework v4.5, нужно убедиться что он установлен). PowerShell Core основан на .Net Core;
- Windows PowerShell работает только на ОС семейства Windows, а PowerShell Core является кроссплатформенным и будет работать в Linux;
- В PowerShell Core нет полной совместимости с Windows PowerShell, однако Microsoft работает на улучшением обратной совместимости со старыми командлетами и скриптами (перед переходом на PowerShell Core рекомендуется протестировать работу старых PS скриптов). В PowerShell 7 обеспечивается максимальная совместимсть с Windows PowerShell.
- Редактор PowerShell ISE нельзя использовать для отладки скриптов PowerShell Core (но можно использовать Visual Studio Code)
- Т.к. Windows PowerShell более не развивается, рекомендуется постепенно мигрировать на PowerShell Core.
Как узнать версию PowerShell из консоли?
Самый простой способ определить какая версия PowerShell у вас установлена с помощью команды:
host
Следующий скриншот из Windows 10, в которой как и в Windows Server 2016 по умолчанию установлен PowerShell 5.1.
или
$PSVersionTable
Можно получить только значении версии:
$PSVersionTable.PSVersion.major
(в этом примере мы получили версию PSVersion 2.0 с чистого Windows Server 2008 R2)
Команда
$PSVersionTable
корректно работает в PowerShell Core на различных операционных системах.
Также можно узнать установленную версию PowerShell через реестр. Для этого нужно получить значение параметра PowerShellVersion из ветки реестра HKLM\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine с помощью Get-ItemProperty
(Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine -Name 'PowerShellVersion').PowerShellVersion
Данный способ работает, начиная с Windows Server 2012/Windows 8. В Windows Server 2008 R2/ Windows 7 нужно получить значение параметра реестра в другой ветке:
(Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine -Name 'PowerShellVersion').PowerShellVersion
Для определения установленной версии PowerShell Core нужно использовать команду:
(Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\PowerShellCore\InstalledVersions* -Name 'SemanticVersion').SemanticVersion
Получаем версию PowerShell на удаленных компьютерах
Для получения версии PowerShell на удаленных компьютерах нужно использовать значение переменной окружения $PSVersionTable или получать данные непосредственно из реестра. Другие способы могут возвращать некорректные данные.
Вы можете получить версию PowerShell с удаленного компьютера с помощью команды Invoke-Command:
Invoke-Command -ComputerName dc01 -ScriptBlock {$PSVersionTable.PSVersion} -Credential $cred
Major Minor Build Revision PSComputerName ----- ----- ----- -------- -------------- 5 1 14393 3383 dc01
Можно получить установленные версии PowerShell с нескольких компьютеров таким скриптом (их список сохранен в текстовом файле):
Invoke-Command -ComputerName (Get-Content C:\PS\servers.txt) -
ScriptBlock{$PSVersionTable.PSVersion} | Select PSComputerName, @{N="PS Version";E={$_.Major}}
Либо можно получить список компьютеров домена через Get-ADComputer и получить версию PowerShell на них:
$adcomputer=(Get-ADComputer -Filter 'operatingsystem -like "*Windows server*" -and enabled -eq "true"' -SearchBase ‘OU=servers,dc=winitpro,dc=ru’ ).Name
Invoke-Command-ComputerName $adcomputer -Scriptblock{$PSVersionTable.psversion} -ErrorAction SilentlyContinue
Если ваш скрипт PoweShell использует специальный функционал определенной версии PS, вы можно принудительно переключиться в режим другой версии PowerShell. Например, для запуска консоли в режиме PowerShell v3, выполните (должен быть установлен .Net Framework 3.5):
PowerShell.exe -version 3
Определение версии PowerShell может быть важно при выполнении скриптов и запуске команд, которые используют командлеты или специальные возможности определенной версии PS. Если вы хотите в скрипте PS определить какая версия PowerShell установлена, и в зависимости от этого использовать разные командлеты, вы можете использовать такой скрипт:
$ps_version = $PSVersionTable.PSVersion.major
if ( $ps_version -eq "2” )
{
write "Вы используете Powershell 2.0"
}
elseif ( $ps_version -eq "5" )
{
write " Вы используете Powershell 5"
}
В следующей статье мы рассмотрим, как обновить версию PowerShell в Windows.
Все способы:
- Шаг 1: Проверка обновления SP1
- Шаг 2: Установка универсальной среды C
- Шаг 3: Установка WMF 5.1
- Шаг 4: Запуск и обновление PowerShell
- Установка последней версии PowerShell через GitHub
- Вопросы и ответы: 3
Шаг 1: Проверка обновления SP1
Официально обновление SP1 для Windows 7 уже не поддерживается разработчиками, однако сейчас все еще можно его установить, если этот апдейт не был добавлен в операционную систему. Его наличие обязательно для дальнейшей установки или обновления PowerShell, поэтому выполните этот шаг, перейдя к инструкции по ссылке ниже.
Подробнее: Обновление Windows 7 до Service Pack 1
Шаг 2: Установка универсальной среды C
Второй этап — установка универсальной среды C, которая необходима для корректного выполнения следующих программ и запуска PowerShell в Windows 7. Ее инсталляция производится с официального сайта через автономный установщик обновлений WUSA.
Перейти к скачиванию универсальной среды C с официального сайта
- Кликните по предыдущей ссылке и после перехода начните загрузку рассматриваемого компонента.
- Откройте полученный архив и найдите совместимый с вашей Виндовс 7 пакет обновления. Скорее всего, это будет Windows6.0 или Windows6.1 с учетом разрядности. Если после запуска вы получили уведомление о том, что обновление недоступно для этого ПК, попробуйте открыть другой MSU-файл.
- Начнется поиск обновлений, занимающий некоторое время.
- Далее появится уведомление об установке KB3118401, которое необходимо подтвердить.
- Запустится процесс инсталляции обновления — следите за его прогрессом в этом же окне.
По завершении рекомендуется перезагрузить компьютер, после чего приступайте к добавлению следующих компонентов.
Шаг 3: Установка WMF 5.1
Если выше мы разобрали вспомогательные компоненты, требуемые для корректной работы PowerShell, то WMF (Windows Management Framework) как раз напрямую связан с этим компонентом и позволяет ему в полной мере использовать встроенные скрипты, в том числе и для обновления до последней версии.
Перейти к скачиванию WMF с официального сайта
- Оказавшись на странице загрузки обновления, нажмите по ссылке «WMF 5.1», находящейся в таблице сравнения версий операционных систем.
- После открытия новой страницы щелкните на «Download», перейдя тем самым к выбору файлов для скачивания.
- Отметьте маркерами только версии для Windows 7, соответствующие разрядности «семерки».
- Запустите находящийся в архиве файл MSU и дождитесь поиска подходящих обновлений.
- Подтвердите уведомление об их инсталляции.
- При отображении сообщения о необходимости перезагрузки ОС сделайте это, чтобы PowerShell был успешно интегрирован.
Шаг 4: Запуск и обновление PowerShell
После перезагрузки компьютера PowerShell уже будет добавлена в Windows: вы сможете запустить ее и проверить обновления через загруженный ранее установочный пакет. Если же нужды в последней версии оснастки нет, просто переходите к ее стандартному использованию.
- Откройте «Пуск», найдите там Windows PowerShell и запустите это приложение.
- Далее перейдите к скачанному ранее архиву, где помимо файла MSU располагался скрипт для PowerShell. Перетащите его на рабочий стол для распаковки.
- Теперь перетащите его в PowerShell и дождитесь появления новой строки.
- Запустите скрипт, нажав клавишу Enter.
Если же на экране появилась ошибка, значит, приложение не нуждается в обновлении.
Установка последней версии PowerShell через GitHub
Как альтернативный вариант разберем скачивание отдельного приложения с PowerShell через GitHub. Его последняя версия устанавливается рядом с классической оболочкой и может работать параллельно.
Перейти к скачиванию последней версии PowerShell с GitHub
- После перехода по ссылке выше найдите таблицу с наименованиями поддерживаемых платформ, где выберите свою версию Windows и скачайте стабильную версию приложения.
- По окончании загрузки запустите установщик.
- В нем переходите к следующему шагу.
- Выберите место на компьютере, куда хотите установить программу.
- Ознакомьтесь с дополнительными опциями перед установкой и отметьте галочкой те параметры, которые хотите применить.
- Ожидайте окончания установки, а затем найдите исполняемый файл PowerShell 7 на рабочем столе или в «Пуск».
- После запуска попробуйте ввести любой скрипт, чтобы удостовериться в нормальной работе консоли.
Наша группа в TelegramПолезные советы и помощь
You may want to know the PowerShell version installed on your machine. While novice users may go to Programs in the Control Panel to check the PowerShell version, it’s often quite the disappointment when they don’t find PowerShell listed as a program there. Instead, you’ll need to resort to other methods to find the PowerShell version.
This article provides a comprehensive guide to checking the PowerShell version you’re running.
Introduction to PowerShell Versions
PowerShell has evolved from a Windows management tool to a versatile shell that can be used across different platforms. In particular, PowerShell Core 6.x and PowerShell 7.x turned it into a powerful, cross-platform automation and scripting framework.
PowerShell Versions Evolution from 1.0 to 7.x
In 2006, Microsoft launched PowerShell 1.0 as part of the .NET framework for the Windows operating system, including Windows XP (SP2), Windows Server 2003 (r2 SP1), and Windows Vista. It introduced cmdlets like Get-Process and Get-Service and was designed to automate tasks in Windows environments.
Version | Description |
---|---|
PowerShell 2.0 | PowerShell 2.0 came in 2009. Amongst other things, it introduced remoting (via WinRM) to run commands on remote machines and the Integrated Scripting Environment (ISE) application. |
PowerShell 3.0 | PowerShell 3.0, released in 2012, introduced workflows, new cmdlets and scheduled jobs for task automation. |
PowerShell 4.0 | PowerShell 4.0 (2013), 5.0 (2016), and 5.1 (2016) had improvements in cmdlets, performance, and DSC. Classes and Enums were added to the scripting language. With PowerShell 5.1, there was a shift towards open-source and PowerShell Core. |
PowerShell Core 6.x | Then PowerShell Core 6.x (2018) was open-sourced and moved to GitHub. It was cross-platform, running on Windows, macOS, and Linux. Not only that, but it was also built for heterogeneous environments and the hybrid cloud. |
PowerShell 7.x | PowerShell 7.x (2020) is the most recent version. It unifies Windows PowerShell and PowerShell Core into a single version stream, supports pipeline parallelization, and improves error handling amongst other things. |
Why identify the correct PowerShell version
Before you use PowerShell for your everyday tasks, one question you may ask is, what version of PowerShell do I have? Having an answer to this question is important because your PowerShell version determines what cmdlets and functions you can use. For this and many other reasons, you must identify which PowerShell version you need to manage your tasks.
- Compatibility. Some scripts or modules require specific cmdlets or features that are available only in the latest PowerShell version. Modern PowerShell versions support older scripts, but with deprecation warnings for outdated features.
- Accuracy in Results. Some PowerShell versions may not yield accurate results you’re looking for, such as when you must meet a specific requirement or prerequisite to run a command or load a module.
- Cross-Platform Support. For Linux or macOS, you need PowerShell Core or PowerShell 7.x.
- Advanced features. Older versions do not support the latest features, such as pipeline parallelism, ?? (null coalescing operator), and ForEach-Object -Parallel, that are available in PowerShell 7.x.
- Cloud and DevOps Integration. Recent PowerShell versions provide enhanced integration capabilities with cloud platforms, such as Azure, AWS), DevOps tools, and CI/CD pipelines, facilitating cloud-based management.
- Security Requirements. The latest PowerShell versions are recommended for security and compliance reasons.
- Environment Setup. To use tools or automations across the environment, knowing the version helps ensure compatibility across systems.
Differences between Windows PowerShell and PowerShell Core
Key differences between Windows PowerShell and PowerShell Core are:
Feature | Windows PowerShell | PowerShell Core |
Platform | Windows-only | Cross-platform (Windows, macOS, Linux) |
Version | Last major version: 5.1 | Ongoing releases (7.x and beyond) |
Framework | Based on .NET Framework | Based on .NET Core (now .NET) |
Release Model | Only bug/security fixes | Active development with new features |
Installation | Is pre-installed with Windows OS | Has to be downloaded separately from GitHub or package managers |
Backward Compatibility | Tight integration with Windows (e.g., WMI, COM) | May have limited Windows-specific features |
Performance | Faster in some Windows-native scenarios | Better performance on multiple platforms |
Module Compatibility | Supports many legacy modules | Some older modules may not be compatible |
Cloud/Container Support | Limited support for containers and cloud environments | Better support for containers and cloud |
Open Source | Proprietary | Open-source (MIT license) |
If you use legacy Windows-specific features or modules, Windows PowerShell is a better choice. But for cross-platform development and cloud-based workflows, PowerShell Core serves best.
How to Check PowerShell Version
Knowing the installed version of PowerShell is important for several practical reasons, as your version determines what cmdlets and functions are available for use. Different versions may offer varied support for different scripts, modules, and platforms. For smooth PowerShell operations, you must know the PowerShell version you are using, its limitations, and its core features.
How to check the PowerShell version is a simple task. The easiest way to check the PowerShell version is through PowerShell itself. You can show the PowerShell version you’re using, for example, via the PSVersionTable.PSVersion or the Get-Host cmdlet.
PowerShell Version Command: $PSVersionTable.PSVersion
This is the most reliable method to get your PowerShell version as it returns information specifically about the PowerShell engine version.
$PSVersionTable.PSVersion
This cmdlet displays the major, minor, and build (patch) version of the installed PowerShell. The revision number is displayed if applicable.
If you want to view more details than just the version, try the following cmdlet:
$PSVersionTable
$PSVersionTable shows several environment-specific properties in addition to the version.
- PSVersion – Shows the PowerShell version
- PSEdition – Shows whether it’s Desktop (Windows PowerShell) or Core (PowerShell Core / PowerShell 7+)
- WSManStackVersion – Shows the version of WS-Management (used for remoting)
- PSRemotingProtocolVersion – Remoting protocol version
- SerializationVersion – Used to maintain compatibility with older versions for remote sessions
How to Get PowerShell Version with Get-Host Command
A host is a program that hosts the PowerShell engine. And you can have a host with a version that is independent of PowerShell.
The following cmdlet outputs the PowerShell version you’re running, but then this version can be inaccurate as it reflects host version, not engine version.
Get-Host
Oftentimes, the PowerShell version matches that of the host. In addition to the host version, this cmdlet also displays the name of the host, current culture, and UI culture.
The Get-Host command does not work remotely and always returns version 1.0.0.0.
$Host and $Host.Version Commands
$host is an automatic variable that displays the same information as the Get-Host cmdlet.
$host
If you are looking for the PowerShell version, $host is not recommended for the same reasons as Get-Host. The same is true for $host.Version.
$host.Version
It displays the version of the host application that is running the current PowerShell session, though in a different format.
Registry Editor
You can check the PowerShell version through the Registry Editor in any of the following ways:
- Use the Get-ItemProperty cmdlet to query the registry for the installed PowerShell version.
- Go to Registry Editor and manually locate the paths for PowerShell version details.
Via Cmdlets
For PowerShell version 5
You can view the PowerShellVersion registry key with the ‘Get-ItemProperty’ cmdlet. It is as:
(Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine -Name 'PowerShellVersion').PowerShellVersion
For PowerShell version 7
If you have PowerShell 7 or later installed, use the following cmdlet:
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\PowerShellCore' | Select-Object -Property PSVersion
Manual method
You can get the PowerShell configuration and version information in the Registry Editor.
For PowerShell version 5
In the Registry editor, expand Computer > HKEY-LOCAL-MACHINE > SOFTWARE > Microsoft > PowerShell >3 > PowerShellEngine. In the adjacent pane, you will find information including the PowerShell version number.
For PowerShell version 7
If you have PowerShell 7 installed, go to the following path in the Registry Editor to check the version:
Computer > HKEY_LOCAL_MACHINE > SOFTWARE > Microsoft > PowerShellCore > InstalledVersions > 31ab5147-9a97-4452-8443-d9709f0516e1
Advanced Techniques for Version Identification
Find PowerShell Version on Remote Systems
Prerequisites
The following prerequisites must be met before you can check the PowerShell version on a remote machine.
- Windows Management Framework (WMF) is installed and enabled on the remote machine.
- WinRM (Windows Remote Management) is configured and running on both the local and remote machines.
Run ‘winrm quickconfig’ to prepare a machine to be remotely accessed via PowerShell. - You have the required permissions on the remote machine.
Check PowerShell version on a remote machine
Use the Invoke-Command cmdlet with $PSVersionTable to check the PowerShell version installed on a remote computer.
Invoke-Command ` -ComputerName WS16-DC1 ` -ScriptBlock { $PSVersionTable.PSVersion } ` -Credential $cred
Note:
- In this command, replace the ComputerName (WS16-DC1) with your specific computer name, and the credentials below $cred with a valid username and password.
- By using commas to separate values, you can effectively handle several remote computers at once.
In the above cmdlet:
- Invoke-Command is used to run commands on a remote computer.
- ComputerName WS16-DC1 specifies the name of the remote computer (WS16-DC1 in this case).
- ScriptBlock {$PSVersionTable.PSVersion} is the script block that is run on the remote computer to retrieve the PowerShell version information.
- Credential $cred specifies the credentials to authenticate on the remote computer, where $cred is an object that contains valid credentials (such as a username and password).
PowerShell Version Comparison Across Windows Operating Systems
This table lists the PowerShell versions pre-installed with different Windows operating systems:
PowerShell Version | Release Date | Windows OS Supported by Default |
PowerShell 1.0 | November 2006 | Windows Server 2003 SP1 Windows XP SP2 Windows Vista |
PowerShell 2.0 | October 2009 | Windows Server 2008 R2 Windows 7 |
PowerShell 3.0 | September 2012 | Windows Server 2012 Windows 8 |
PowerShell 4.0 | October 2013 | Windows Server 2012 R2 Windows 8.1 |
PowerShell 5.0 | February 2016 | Windows Server 2016 Windows 10 |
PowerShell 5.1 | August 2016 | Windows Server 2016 Windows 10 anniversary update |
PowerShell Core 6.0 | January 2018 | Windows Server 2012 R2 Windows Server 2012 Windows Server 2016 Windows 10 Windows 8.1 Windows 7 with Service Pack 1 |
PowerShell 5.1 is the last version installed by default on Windows clients and servers. It has been succeeded by PowerShell Core (now PowerShell 7), which is a separate product. It does not come pre-installed but has to be manually installed.
Installing a newer version does not replace the default pre-installed version. For example, PowerShell 7.x and Windows PowerShell 5.1 can co-exist.
Update or Install Newer PowerShell Versions
To stay up to date on Windows PowerShell 5.1 in Windows 10 and 11, always run system updates to keep your PC up to date.
PowerShell Core (version 7) is a different product from Windows PowerShell and must be installed manually via any of the following methods:
- Download and run the installer file
- Run a command from PowerShell on your computer
As a recommendation, keep both Windows PowerShell and PowerShell Core on your computer to get the most out of PowerShell. Beware that older scripts may not work in newer versions and current scripts may not work in older versions.
You can download and install a newer PowerShell version in any of these ways.
Install PowerShell Using Microsoft Store
On Windows 10 and Windows 11, open the Microsoft Store and search for PowerShell.
The latest version of the PowerShell app is listed in the search results as PowerShell (published by Microsoft Corporation). Click it to view its details, where you can also click Get to download and install it.
Install PowerShell Using Winget
The WinGet package manager installs the latest PowerShell version from the command line.
Search for PowerShell using Winget
To view a list of packages related to PowerShell, with their version numbers and IDs, use the following cmdlet:
winget search PowerShell
Install PowerShell
Locate the required PowerShell package and install it using its ID. The ID for PowerShell is Microsoft.PowerShell.
To install the latest PowerShell version, use the following cmdlet:
winget install Microsoft.PowerShell
Install PowerShell Using MSI Package
Another method is to download PowerShell from GitHub and use the MSI for installation. Visit the official PowerShell GitHub release page to locate the most recent PowerShell release (such as PowerShell 7.x). Scroll down to the Assets section of this release and download the MSI package.
The package takes some time to download. Once downloaded, run the installer to install PowerShell.
Managing Multiple PowerShell Versions
You can use the classic Windows PowerShell (usually version 5.1) and the modern PowerShell Core (versions 6.x and 7.x) on the same machine without conflicts.
A common use case for managing multiple PowerShell versions is when different environments or scripts require specific versions.
Here’s how you can manage multiple versions of PowerShell on your system.
Run a Specific Version from the Run dialog box or the Command Line
Open the Run dialog box and specify the path to the exe file of a PowerShell version to launch it (see the example below).
You can also run a specific PowerShell version by specifying its path in PowerShell, as provided in the following example. Note that this method is only valid for PowerShell 7, where you can switch between versions.
Example:
- PowerShell 5.1
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
- PowerShell 7
C:\Program Files\PowerShell\7\pwsh.exe
PowerShell Profiles and Configuration
A PowerShell profile is a PowerShell script that runs every time you launch PowerShell, except when you use the -NoProfile flag.
Each PowerShell version has its own profile file. If you want specific settings or configurations to be available in one version and not in the other, you have the option to configure the profile separately for each version.
Locate the profile file manually
- PowerShell 5.1 profile might be at: C:\Users\<username>\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
- PowerShell 7+ profile might be at: C:\Users\<username>\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
Locate the profile file through PowerShell
You can also use PowerShell itself to retrieve the PowerShell profile. Simply use $Profile to locate the profile path, as the $Profile variable stores the path.
$Profile
This displays the path to the current user’s PowerShell host application profile. You can pipe the $Profile variable to the Get-Member cmdlet to get additional paths.
$Profile | Get-Member -MemberType NoteProperty
Test for Compatibility with Older Scripts and Modules
It is important to test for compatibility with older scripts and modules in PowerShell when upgrading to newer versions or integrating legacy code.
Following are some ways to test for compatibility with older scripts and modules.
Use Windows PowerShell and PowerShell Core Side by Side
You can run both Windows PowerShell and PowerShell Core on the same machine. Test your script or module in both environments for compatibility. Remember that 5.1 is the last major release of Windows PowerShell while version 7 is the current release of PowerShell Core.
An example is as:
./your_script.ps1
./ indicates that the script is located in the current directory while your_script.ps1 is the script you are trying to run. .ps1 is the default extension for PowerShell script files.
Check PowerShell Version
It is a good idea to know which version of PowerShell your script was initially written for, and which version you are trying to run it in.
Use the Test-ModuleManifest Cmdlet
The Test-ModuleManifest cmdlet is used to verify that a PowerShell module manifest (.psd1 file) is valid and correctly configured. It also checks the file for dependencies and compatibility issues.
Test-ModuleManifest -Path "C:\Path\To\YourModule.psd1"
The -Path parameter specifies the path to the .psd1 file.
Use the Get-Command Cmdlet to Check Cmdlet Availability
Some cmdlets and parameters may be supported in one PowerShell version and not in another. Use the Get-Command cmdlet to verify the availability and syntax of the cmdlets you are using. Here is an example:
Get-Command -Name Invoke-RestMethod -Module Microsoft.PowerShell.Utility
PSScriptAnalyzer for Static Code Analysis
PSScriptAnalyzer is a tool that checks for best practices and identifies compatibility issues. Use the following cmdlet to install and run it:
Install-Module -Name PSScriptAnalyzer Invoke-ScriptAnalyzer -Path "C:\Path\To\YourScript.ps1"
This is a good way to catch any issues with your scripts or deprecated cmdlets before runtime.
Check for .NET Compatibility
Windows PowerShell (5.1) is built on .NET Framework whereas PowerShell Core (6+) and PowerShell 7+ are built on .NET Core/.NET. In case your script or module relies on .NET assemblies, make sure they are compatible with both .NET Core/.NET and .NET Framework.
You can test the .NET assemblies used in your script with the following cmdlet:
[System.Reflection.Assembly]::LoadFile("C:\Path\To\YourAssembly.dll")
Conclusion
Knowing what version of PowerShell is installed on your computer is important for several reasons. Different versions come with new cmdlets, features, and syntax, so knowing the version ensures that your scripts are compatible with the version you are running them in. PowerShell Core introduced cross-platform compatibility, so knowing the installed version is key to using the right platform-specific features and modules.
Of all the methods available for determining the PowerShell version running on your computer, $PSVersionTable is highly recommended. It is not only the most reliable method, but also the most accurate for version identification. It provides a comprehensive overview of the PowerShell environment, helping you ensure that scripts are compatible with the specific version and environment.
You must regularly update PowerShell to ensure that critical security patches that protect against vulnerabilities found in earlier versions are installed. Moreover, regular update ensures access to the latest features, such as new cmdlets and cross-platform enhancements. It also guarantees improved performance, robust execution policies, and enhanced support for parallel and asynchronous execution. In short, upgrading to the latest PowerShell version helps create more secure, efficient, and scalable automation solutions, while reducing risks associated with outdated or unsupported versions.
FAQ
How to check powershell version?
The easiest way to check the PowerShell version is through PowerShell itself. You can show the PowerShell version you’re using, for example, via the PSVersionTable.PSVersion or the Get-Host cmdlet.
Since 2012, Jonathan Blackwell, an engineer and innovator, has provided engineering leadership that has put Netwrix GroupID at the forefront of group and user management for Active Directory and Azure AD environments. His experience in development, marketing, and sales allows Jonathan to fully understand the Identity market and how buyers think.
Microsoft has made Windows PowerShell available for advanced users and IT administrators for a long time as an advanced form of command prompt. It includes a vast range of ready-to-use cmdlets and comes with the ability to use .NET framework/C# in several techniques.
Windows PowerShell History
Before you find the PowerShell version of Windows 11, 10, 8, or 7, let me explain its history.
- PowerShell V1.0: The first version of Windows PowerShell was released by Microsoft in November 2006 for Windows XP SP2, Server 2003 SP1, and Vista.
- PowerShell V2.0: The PowerShell V2.0 comes in light of the launch of Windows 7 and Server 2008 R2. Apart from that, it was also released as a standalone package for Windows XP SP3, Server 2003 SP2, and Vista SP1.
- PowerShell V3.0: On Windows 8, Microsoft included PowerShell 3.0, which can also be used on Windows 7 SP1, Server 2008 SP1, and Server 2008 R2 SP1. However, Microsoft removed its support from Windows XP.
- PowerShell V4.0: A successor of Windows 8, Windows 8.1 shipped with PowerShell 4.0. Microsoft also made it available for Windows 7 SP1, Server 2008 SP1, and Server 2008 R2 SP1.
- PowerShell V5.0: PowerShell 5.0 was released on February 24, 2016. Later, PowerShell v 5.1 was released along with Windows 10 Anniversary Update. Microsoft also made it available for Windows 7, Server 2008, Server 2008 R2, Server 2012, and Server 2012 R2 users on January 19, 2017.
- PowerShell V6.0: Microsoft first announced PowerShell Core on August 18, 2016, along with their decision to make the product cross-platform, independent of Windows, free, and open source. It was released on January 10, 2018, to Windows, macOS, and Linux users.
- PowerShell V7.0: Microsoft informed us about PowerShell 7.0 on March 4, 2020. Anyone can download and install the latest version of PowerShell from GitHub.
In this gearupwindows article, you will learn to find the PowerShell version on Windows 11, 10, 8, and 7.
How to View PowerShell Version on Windows PCs?
To know the PowerShell version on Windows computers, use the following steps:-
Step 1. First, launch Windows PowerShell.
Step 2. Then, type the following command and press the Enter key on the keyboard:-
$PSVersionTable
Step 3. In the output, beside PSVersion, you can view the PowerShell version.
Besides that, one can also find the PowerShell version by running get-host|Select-Object version or $host.version command.
Conclusion
In conclusion, Windows PowerShell is a powerful tool for advanced users and IT administrators, providing a vast range of ready-to-use cmdlets and the ability to use .NET framework/C# in several techniques. Microsoft has been developing and releasing different versions of PowerShell since 2006, including the cross-platform and open-source PowerShell Core. It is essential to know the PowerShell version on your Windows PC to ensure compatibility and functionality. By following the simple steps mentioned in this article, you can easily view the PowerShell version on Windows 11, 10, 8, and 7.
Windows 10 offers Powershell 5.0 by default, but it gets updated automatically. It is always recommended to update Windows, and so, if you update Windows regularly, the latest Powershell builds will also be installed. However, if you are using an older version of Windows other than Windows 10, then also, you might want to find out what version of Powershell is installed at any instance.
How To Check Powershell Version On Windows 7, 8 & 10
So, today we will be talking about the various methods using which you can find out the Powershell version that is installed on your PC. Before we move on, here’s a table that provides the list of versions that are installed by default.
OS | Powershell Version | Auto Update |
Windows 10 and Windows Server 2016 | PowerShell version 5.0 | Yes |
Windows 8.1 and Windows Server 2012 R2 | PowerShell version 4.0 | No |
Windows 8 and Windows Server 2012 | PowerShell version 3.0 | No |
Windows7 SP1 and Windows Server 2008 R2 SP1 | PowerShell version 2.0 | No |
So, if you aren’t updating Windows, then you should have these versions of Powershell by default. Other than that, there are quite a few ways to find out the Powershell version.
Method 1: Via Powershell itself
- Press
Windows key + R
to open up a Run command. - Type
powershell
and press Enter. - A new PowerShell prompt will be open.
- In the newly opened window, type
$PSversionTable
and hit enter. - A list of details related to PowerShell will be displayed.
- Check the first entry against
PSVersion
. - That value is the version of Powershell installed on your PC.
Method 2: Using Registry Editor
- On Windows 10, you can just search for
regedit
in the search bar and click on Registry Editor to open it. On older versions of Windows, however, you need to pressWindows Key+R
and then typeregedit
and hit enter to open it up. - Once it is open, navigate to
HKLM:\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine
- There will be a key called
PowerShellVersion
, and it will have a value that denotes the Powershell version that is installed on your PC.
Method 3: Via (Get-Host).Version
PowerShell has a concept known as hosts
. A host is a program that is hosting the PowerShell engine. The PowerShell console or any code editor with an integrated terminal is PowerShell host
. You can just run (Get-Host).Version
and it will return a version number, but it may not always be the PowerShell engine version. Here are the steps to try this one.
- Press
Windows key + R
to open up a Run command. - Type ‘powershell’ and press Enter.
- A new PowerShell prompt will be open.
- In the newly opened window, type
(Get-Host).Version
and hit enter. - There will be some texts which mention
Major
,Minor
,Build
&Revision
along with the values. So, adding a decimal point between the values will give you the version details.
Method 4: For Remote PCs
If you want to get the Powershell version details of a remote computer, you can try the something similar to Method 2, but with a little change.
- Press
Windows key + R
to open up a Run command. - Type
powershell
and press Enter. - A new PowerShell prompt will be open.
- In the newly opened window, type
Invoke-Command -ComputerName 10.0.0.5 -ScriptBlock {(Get-Host} -Credential $cred
and, hit enter.
- There will be some texts which mention
Major
,Minor
,Build
&Revision
along with the values. So, adding a decimal point between the values will give you the version details.
NOTE: The IP values may be different based on your own configuration, so if you know what you are doing, there shouldn’t be any issues.
Method 5: Via $host
This method is similar to Method 1, with one minor change. Here’s what you need to do.
- Press
Windows key + R
to open up a Run command. - Type
powershell
and press Enter. - A new PowerShell prompt will be open.
- In the newly opened window, type
$host
and hit enter. - A list of details related to PowerShell will be displayed.
- Check the second entry, against Version.
- That value is the version of Powershell installed on your PC.
Method 6: Via $PSVersionTable.PSVersion
This one is similar to Method 3, with one minor change.
- Press
Windows key + R
to open up a Run command. - Type
powershell
and press Enter. - A new PowerShell prompt will be open.
- In the newly opened window, type
$PSVersionTable.PSVersion
and hit enter. - There will be some texts which mention
Major
,Minor
,Build
&Revision
along with the values. So, adding a decimal point between the values will give you the version details.
NOTE: This method is better that will always show the values related to the PowerShell engine itself.
Method 7: Same as Method 6, for Remote PCs
This one is similar to what we did for Method 4, but it is more accurate. Here’s how to try looking for the version details using this method.
- Press
Windows key + R
to open up a Run command. - Type
powershell
and press Enter. - A new PowerShell prompt will be open.
- In the newly opened window, type
Invoke-Command -ComputerName 10.0.0.5 -ScriptBlock {$PSVersionTable.PSVersion} -Credential $cred
and, hit enter.
- There will be some texts which mention
Major
,Minor
,Build
&Revision
along with the values. So, adding a decimal point between the values will give you the version details.
Method 8: Using CMD
When in doubt, rely on something that has been on Windows for a decade now- CMD. Here is how you can use CMD to check the Powershell version.
- Press
Windows key + R
to open up a Run command. - Type
cmd
and press Enter. - A window will open.
- In the newly opened window, type
reg query HKLM\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine /v PowerShellVersion
and, hit enter.
- It will directly show the Powershell version.
These are the various ways you can use to check the version of Powershell installed on your PC. However, we recommend using the preferred methods for more accurate results.