Powershell what is windows version

Как узнать версию PowerShell в Windows 10, 8.1, 8, 7

В данной статье показаны действия, с помощью которых можно узнать установленную версию Windows PowerShell в операционных системах Windows 10, 8.1, 8, 7.

PowerShell — это оболочка командной строки с поддержкой задач и язык скриптов на основе платформы .NET.

PowerShell позволяет системным администраторам и опытным пользователям быстро автоматизировать задачи для управления операционной системой и поэтому всегда рекомендуется убедиться, что ваша система использует последнюю версию PowerShell.

Чтобы узнать установленную версию PowerShell, запустите консоль Windows PowerShell любым из способов и выполните следующую команду:

В строке PSVersion вы увидите версию PowerShell.

Также, чтобы узнать версию PowerShell, можно использовать дополнительные команды:

Результат выполнения команд показан на скриншоте ниже.

Ниже приведены версии, которые устанавливаются по умолчанию в соответствии с версией Windows:

  • Windows 10 (см. примечание) PS 5.1
    Windows Server 2016
  • Windows 8.1PS 4.0
    Windows Server 2012 R2
  • Windows 8PS 3.0
    Windows Server 2012
  • Windows7 с пакетом обновления 1 (SP1)PS 2.0
    Windows Server 2008 R2 с пакетом обновления 1 (SP1)
  • Если в начальном выпуске Windows 10 включены автоматические обновления, PowerShell обновляется с версии 5.0 до 5.1
  • Если оригинальная версия Windows 10 не обновлена в Центре обновления Windows, версия PowerShell будет 5.0

Как узнать какая версия PowerShell установлена?

В этой статье мы рассмотрим какие версии PowerShell существуют, в чем отличие Windows PowerShell от PowerShell Core и как узнать, какая версия 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)

Стоит обратить внимание, что последние 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.
Читайте также:  Создание домашней сети windows 10 через роутер

Как узнать версию PowerShell из консоли?

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

Можно получить только значении версии:

(в этом примере мы получили версию 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

(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

Можно получить установленные версии PowerShell с нескольких компьютеров таким скриптом (их список сохранен в текстовом файле):

Invoke-Command -ComputerName (Get-Content C:\PS\servers.txt) —
ScriptBlock <$PSVersionTable.PSVersion>| Select PSComputerName, @>

Либо можно получить список компьютеров домена через 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.

Use PowerShell to Find Operating System Version

April 25th, 2014

Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to find the version of his Windows operating system.

Microsoft Scripting Guy, Ed Wilson, is here. It is not a secret that I love Windows PowerShell. It is not a secret that I also love Windows 8.1 especially on my Surface Pro 2.

Читайте также:  Темы иконок для linux mint

Disclaimer: I bought my Surface Pro 2 myself at the Microsoft Store in the mall. I paid the same price as everyone else does, and Istood in line to make the purchase just like everyone else does. I did so because I wanted one to take with me on my five week trip to Europe. It absolutely rocked.

Anyway, I love Windows PowerShell so much that I spend a lot of time playing around with it. I was on the Sapien blog the other night, and I ran across the following post by my friend, Alexander Riedel: Windows 8.1 breaks the version API. I thought to myself, «Hmmmm, I need to test this out.» In particular, he was referring to using the static OSVersion property from the System.Environment class in .NET. Here is the code:

When I opened the Windows PowerShell console to test this, I found that it works just fine. The code and associated output is shown here:

Well, I know that Alexander is a very intelligent and careful person. He certainly wouldn’t make wild accusations without backup or proof. So I opened the Windows PowerShell ISE and typed the same code. The results are shown here:

So it would seem that his blog post is correct. Except, it is not actually broken, and Alexander points to the Microsoft page that shows that this API is in fact deprecated in Windows 8.1: Operating system version changes in Windows 8.1 and Windows Server 2012 R2.

Deprecated, as you may know, means that you should quit using it because in future versions it may be removed and may no longer be supported. Sometimes a deprecated API works—other times it gives inconsistent results, as is the current case. The article states that the reason for this move is that a number of applications do not get shimmed properly because of poor version checks. For example, an application written for Windows XP would test for that version, and even though the app would work on Windows 8.1 it would refuse to run because it was specifically checking for Windows XP. The way around this, is to use an application manifest, which is something that most Windows PowerShell scripters will not be doing.

Testing out a theory

So I decided to test out a theory. I wonder if the GetVersion function would still work if I get it directly from the Kernel32.dll. I wrote a function that I call Get-OSVersion to see if it will work.

The first thing I need to do is to go to Pinvoke.net and find the signature that I will need to use with the Add-Type command. Upon arriving at the site, I want to find Kernel32 in the left pane, and then under that section, I want to find the GetVersion function. This is pretty straightforward, and the site is shown in the following image:

Now that I have my signature, I use a HereString to store the signature as shown here:

public static extern uint GetVersion();

Читайте также:  Install ssh server on windows server

Now, I need to use the Add-Type cmdlet to add definition. I use –PassThru because I want the object that is created to be available to me. The command is shown here:

Add-Type -MemberDefinition $signature -Name «Win32OSVersion» -Namespace Win32Functions -PassThru

That is all there is to my function, so I close out the curly braces. The more complicated part of this comes in trying to parse the DWORD that the GetVersion function returns. So the first thing I need to do is convert the DWORD into bytes. To do this, I use the System.BitConverter .NET Framework class and I call the static GetBytes method. I pass it the function Get-OSVersion that I created, and I call the static GetVersion method from my object. This line is shown here:

The $OS variable contains an array of four bytes. The first element in the array contains the major version number, the second element contains the minor version. Because an array begins with 0, I grab elements 0 and 1 and store them in the appropriate variables as shownhere:

I need to take an array of the last two bytes and convert them from bytes into an integer. To do this, I once again use the System.BitConverter .NET Framework class, and I call the static ToInt16 method. It accepts an array and a position in the array as arguments. Here it is easy. My array is elements 2 and 3, and I start at the first position in the newly created array. This will be my build number. Here is the command that does this:

The last thing to do is display some output. I thought about creating an object. But dude, for this I was only trying to see if it worked. So I created a string by using the format specifier and substitution values.

For each portion in the following command, I substitute the value that is in the other side of the –F that occupies that position. So <0>will be replaced by the first item in my list—in this example, that is the value stored in the $MajorVersion variable.

«Version is <0>. <1>build <2>» -F $majorVersion,$minorVersion,$buildNumber

After all that work (it took me about an hour to write this), I finally run the script. And what happens? Yep, I proved that it lies about the operating system version. This is shown here:

So what is the answer? Dude (or dudette), it is easy. Use WMI. Here is the WMI code:

Note Remember, this is only a problem in Windows 8.1, so you should definitely be using Get-CimInstance and NOT using Get-WMIObject.

Here is the output. I see that it works properly, and it was a heck of a lot easier than messing around with the Kernel32 API:

That is all there is to using Windows PowerShell to find Windows operating system version information. Poshpourri Week will continue tomorrow when I will have a guest blog post from newly minted Windows PowerShell MVP, Dave Wyatt. The post is cool, and you don’t want to miss it.

Оцените статью