Как узнать версию powershell windows server 2008 r2

В данной статье мы рассмотрим, как посмотреть версию PowerShell и при необходимости обновить ее до последней версии.

Обновлено 18.05.2022

powershellДобрый день! Уважаемые читатели и гости IT блога Pyatilistnik.org. В прошлый раз мы с вами рассмотрели методы открытия PowerShell в операционных системах Windows. Представим себе ситуацию, что вы прочитали статью, в которой рассказывалось решение какой-то проблемы с помощью скрипта PowerShell и новых командлетов. Вы пытаетесь все это дело повторить. но у вас выскакивает ошибка, что командлетов не обнаружено. Такая ситуация получается по ряду причин и самая распространенная, это старый выпуск оболочки. В данной статье мы рассмотрим, как посмотреть версию PowerShell и при необходимости обновить ее до последней версии.

История версий PowerShell

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

  • PowerShell версии 1 — вышел в 2006 году, и был включен в состав Windows Server 2003 SP1 и как для меня стало удивительным в будущем аж в сам XP.
  • PowerShell версии 2.0 — появился в легендарной операционной системе Windows 7 и Windows Server 2008 R2. Большая часть людей стала с ним знакомится именно с данных времен.
  • PowerShell версии 3.0 — Стал доступен с выходом Windows 8 и Windows Server 2012.
  • PowerShell версии 4.0 — Вошел в состав Windows 8.1 и Windows Server 2012 R2.
  • PowerShell версии 5.0 — Вышел в 2016 году. Данный релиз не привязывался к конкретной ОС.
  • PowerShell версии 5.1 — Стал частью Windows Server 2016 и Windows 10, в январе 2017 года.
  • PowerShell версии 6.0 — Идет в составе Windows 10 1703 и Windows Server 2019

Хочу отметить, что вы можете установить самую свежую версию языка управления даже в самой старой Windows 7. Подробнее про функционал в каждой версии вы можете посмотреть в Википедии (https://en.wikipedia.org/wiki/PowerShell#PowerShell_1.0)

Как проверить версию PowerShell из оболочки

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

$PSVersionTable.PSVersion

В итоге моя Windows 10 1803 вывела мне версию 5.1 билд 17134.

Версия powershell windows 10 1803

Та же команда, но уже в Windows 8.1.

Версия powershell windows 8.1

Можно применить вот такой метод проверить версию PowerShell:

Get-Host | Select-Object Version

В результате я получил строку результата вот такого вида 5.1.17134.407.

проверить версию powershell Windows 10

Есть еще несколько команд:

(Get-Host).Version или $host.version

Методы узнать версию powershell

Благодаря команде $host.version | Out-GridView вы выведете результат с версией установленной PowerShell в вашей системе, в красивом отдельном окне.

Вывод версии powershell в отдельном окне

Еще чуть не забыл вот такой метод:

Write-Host (get-host).Version.Major (Get-Host).Version.Minor -Separator .

как узнать версию powershell

Посмотреть версию PowerShell можно и простенькой командой Get-Host.

get-host

Версия PowerShell прекрасно выводится и вот таким кодом:

Get-Variable | where {$_.Name -Like ‘*version*’} | %{$_[0].Value}

версия powershell

Как проверить версию PowerShell через реестр Windows

Я вам не перестаю повторять, что любые команды из оболочки или cmd, всего лишь обращаются к разделам реестра Windows и берет от туда нужную информацию. В реестре есть ветка:

HKEY_LOCAL_MACHINESOFTWAREMicrosoftPowerShell3 PowerShellEngine

Тут будет ключ реестра PowerShellVersion.

версия powershell через реестр

Как получить версию PowerShell на удаленных хостах в домене

Если у вас установлена служба Active Directory и вы понимаете все плюсы домена, то вы можете удаленно посмотреть версию PowerShell. Выполните команду в оболочке пошика:

Invoke-Command -Computername client001.root.pyatilistnik.org -Scriptblock {$PSVersionTable.psversion}

получить удаленно версию powershell

Можно для нескольких компьютеров в домене. Сначала получите список имен компьютеров, запустив Get-ADComputer. Затем используйте список, чтобы получить версию powershell для всех компьютеров.

$adcomputer=(Get-ADComputer -Filter *).Name

Invoke-Command-ComputerName $adcomputer-Scriptblock{$PSVersionTable.psversion} -ErrorAction SilentlyContinue

как узнать версию powershell удаленно

Думаю вы разобрались, как узнать версию PowerShell. Далее я вам советую, произвести установку обновлений, если вы выяснили, что у вас не последняя версия. Это процесс подробно описан в данной статье. С вами был Иван Семин, автор и создатель IT блога Pyatilistnik.org.

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

как определить установленную версию powershell из консоли

или

$PSVersionTable

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

$PSVersionTable.PSVersion.major

(в этом примере мы получили версию PSVersion 2.0 с чистого Windows Server 2008 R2)

$PSVersionTable

Команда
$PSVersionTable
корректно работает в PowerShell Core на различных операционных системах.

Также можно узнать установленную версию PowerShell через реестр. Для этого нужно получить значение параметра PowerShellVersion из ветки реестра HKLMSOFTWAREMicrosoftPowerShell3PowerShellEngine с помощью Get-ItemProperty

(Get-ItemProperty -Path HKLM:SOFTWAREMicrosoftPowerShell3PowerShellEngine -Name 'PowerShellVersion').PowerShellVersion

узнать версию powershell xthtp httcnhf

Данный способ работает, начиная с Windows Server 2012/Windows 8. В Windows Server 2008 R2/ Windows 7 нужно получить значение параметра реестра в другой ветке:

(Get-ItemProperty -Path HKLM:SOFTWAREMicrosoftPowerShell1PowerShellEngine -Name 'PowerShellVersion').PowerShellVersion

версия powershell в windows server 2008r2

Для определения установленной версии PowerShell Core нужно использовать команду:

(Get-ItemProperty -Path HKLM:SOFTWAREMicrosoftPowerShellCoreInstalledVersions* -Name 'SemanticVersion').SemanticVersion

Получаем версию PowerShell на удаленных компьютерах

Для получения версии PowerShell на удаленных компьютерах нужно использовать значение переменной окружения $PSVersionTable или получать данные непосредственно из реестра. Другие способы могут возвращать некорректные данные.

Вы можете получить версию PowerShell с удаленного компьютера с помощью команды Invoke-Command:

Invoke-Command -ComputerName dc01 -ScriptBlock {$PSVersionTable.PSVersion} -Credential $cred

получить версию powershell с удаленного компьютера

Major Minor Build Revision PSComputerName
----- ----- ----- -------- --------------
5 1 14393 3383 dc01

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

Invoke-Command -ComputerName (Get-Content C:PSservers.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.

PowerShell 7

The accepted answer is only appropriate if one version of PowerShell is installed on a computer. With the advent of PowerShell 7, this scenario becomes increasingly unlikely.

Microsoft’s documentation states that additional registry keys are created when PowerShell 7 is installed:

Beginning in PowerShell 7.1, the [installer] package creates registry keys
that store the installation location and version of PowerShell. These
values are located in
HKLMSoftwareMicrosoftPowerShellCoreInstalledVersions<GUID>. The
value of <GUID> is unique for each build type (release or preview),
major version, and architecture.

Exploring the registry in the aforementioned location reveals the following registry value: SemanticVersion. This value contains the information we seek.

On my computer it appears like the following:

Path                                                                                           Name              Type Data
----                                                                                           ----              ---- ----
HKLM:SOFTWAREMicrosoftPowerShellCoreInstalledVersions31ab5147-9a97-4452-8443-d9709f0516e1 SemanticVersion String 7.1.3

Image displaying the specified key in the Windows Registry Editor

As you can see, the version of PowerShell 7 installed on my computer is 7.1.3. If PowerShell 7 is not installed on the target computer, the key in its entirety should not exist.

As mentioned in the Microsoft documentation, the registry path will be slightly different dependent on installed PowerShell version.

Part of the key path changing could pose a challenge in some scenarios, but for those interested in a command line-based solution, PowerShell itself can handle this problem easily.

The PowerShell cmdlet used to query the data in this registry value is the Get-ItemPropertyValue cmdlet. Observe its use and output as follows (note the asterisk wildcard character used in place of the part of the key path that is likely to change):

PS> Get-ItemPropertyValue -Path "HKLM:SOFTWAREMicrosoftPowerShellCoreInstalledVersions*" -Name "SemanticVersion"

7.1.3

Just a simple one-liner.

It is important for an administrator to know what Windows PowerShell and PowerShell edition and version are installed on a system, especially due to script compatibility. This article covers all the ways to check the PowerShell version on Windows, Linux, and MacOS and offers tips and tricks. The methods discussed here also work with PowerShell 7, 7.1 and 7.2

Contents

  1. Checking the PowerShell edition
  2. Checking the PowerShell version in Windows
    • Windows PowerShell vs. PowerShell
    • Get-Host cmdlet
    • $Host variable
    • Registry
    • $PSVersionTable variable
    • Checking the PowerShell version on a remote host
  3. Checking the PowerShell version on Linux
  4. Checking the PowerShell version on macOS
  5. Final words
  • Author
  • Recent Posts

Leos has started in the IT industry in 1995. For the past 15+ years he focused on Windows Server, VMware administration and security. Recently, Leos is focusing on automation via Ansible. He is also a Certified Ethical Hacker.

Checking the PowerShell edition

In general, we differentiate between two PowerShell editions:

  1. Desktop—Formerly Windows PowerShell edition, available only in Windows. Its version numbers range from 1.0 to 5.1, which is still the default version in Windows Server 2019/2022 and Windows 10/11. It is part of the operating system.
  2. Core—Cross-platform PowerShell, formerly known as PowerShell Core, is available in Windows, Linux, and MacOS. Its version numbers start at 6 (PowerShell Core); the current version is 7.2.3, known as PowerShell.

The easiest way to check your PowerShell edition is to use an automatic variable, $PSEdition.

Checking the PowerShell edition using the $PSEdition variable

Checking the PowerShell edition using the $PSEdition variable

I will use the edition names throughout the post for clarity.

While it is relatively easy to get the correct version in Linux and MacOS, where you can only have the PowerShell edition, it might be a bit trickier in Windows, where you can have both the Desktop and Core editions.

Checking the PowerShell version in Windows

In Windows, there are four methods for getting the correct version of PowerShell:

  1. Get-Host cmdlet
  1. $Host variable
  2. Registry
  3. $PSVersionTable variable

Some of them are less reliable than others; some do not work properly when called remotely. Before moving forward with them, let’s spend a moment discussing Windows PowerShell vs. PowerShell.

Windows PowerShell vs. PowerShell

As discussed above, Windows is the only system where you can install both PowerShell editions. So, which of them will you query? Will the query return a version of both? This might be a bit misleading, especially for less experienced administrators.

The answer is simple. Windows PowerShell and PowerShell have different and independent executables (and icons). For Windows PowerShell, it is powershell.exe; for PowerShell, it is pwsh.exe.

So, locally, this is easy—it depends on which PowerShell you start and run the query in. Remotely, it is a different story, as you will see below.

Windows PowerShell vs. PowerShell version

Windows PowerShell vs. PowerShell version

Get-Host cmdlet

In PowerShell, a host is a program hosting the PowerShell engine. Visual Studio Code with an integrated terminal is an example of a host. The Get-Host cmdlet returns information about the host, including the version. To display only PowerShell, you can run this command:

(Get-Host).version

Using the Get Host cmdlet

Using the Get Host cmdlet

However, the cmdlet returns the version of the host you are running, not the PowerShell engine itself. These might be different. Also, this cmdlet does not work remotely—it always returns version 1.0.0.0, even on Windows Server 2022.

$Host variable

The $Host variable is an automatic variable, which is the same object that Get-Host returns. As the methods are interchangeable, they might not return the correct engine version, and they don’t work remotely. I do not recommend using these at all. To display the contents of the $Host variable, you can just enter it on the PowerShell console.

Using the $Host variable

Using the $Host variable

Registry

Another option is to use the registry. There are three basic ways to get such information—graphically with regedit, command line with reg query, and PowerShell. As this post is all about PowerShell, let’s look at that method.

[version](Get-ItemProperty -Path HKLM:SOFTWAREMicrosoftPowerShell3PowerShellEngine -Name 'PowerShellVersion').PowerShellVersion
You can also use this method remotely with Invoke-Command.
$script = { [version](Get-ItemProperty -Path HKLM:SOFTWAREMicrosoftPowerShell3PowerShellEngine -Name 'PowerShellVersion').PowerShellVersion }
Invoke-Command -ComputerName srv2022 -ScriptBlock $script

Using registry method locally and remotely

Using registry method locally and remotely

Watch out—running such a command will only return the Desktop edition version. However, new registry keys were added in PowerShell 7.1, and we can now also query the registry for Core installation. The following code will:

  1. Check the registry for the Desktop edition version
  2. Check the registry for the Core edition version (different key)
  3. If it doesn’t find the Core registry key, a warning message is shown
$script = { [version](Get-ItemProperty -Path HKLM:SOFTWAREMicrosoftPowerShell3PowerShellEngine -Name 'PowerShellVersion').PowerShellVersion
try {
[version] (Get-ChildItem -Path HKLM:SOFTWAREMicrosoftPowerShellCoreInstalledVersions -ErrorAction stop | Get-ItemProperty -Name SemanticVersion ).SemanticVersion
 } catch {
 Write-Host "PowerShell 7.1 or higher is not installed, can't query the registry for previous PowerShell Core versions." -ForegroundColor Yellow
 }
}
Invoke-Command -ComputerName srv2019 -ScriptBlock $script

Querying the remote system using the registry method for Desktop and Core editions

Querying the remote system using the registry method for Desktop and Core editions

Although this method is absolutely reliable regarding the returned version, its syntax is quite long for daily usage. Luckily, one other method is available.

$PSVersionTable variable

Last, we’ll look at what is probably the most useful method, another automatic variable called $PSVersionTable. This is a very reliable method that gives you not only the correct PowerShell engine version but also its edition (Desktop or Core). Run this command to expand the version property.

$PSVersionTable.PSversion

Using the $PSVersionTable variable

Using the $PSVersionTable variable

Checking the PowerShell version on a remote host

This method also works well to check the PowerShell version remotely using Invoke-Command.

Querying a remote computer with $PSVersionTable

Querying a remote computer with $PSVersionTable

Watch out—In the screen capture, you can see that I have executed the command in PowerShell 7, but the result I got was version 5.1, which is the Desktop edition.

This happens because, by default, Invoke-Command always connects to the Windows PowerShell remoting endpoint unless otherwise specified. If I want to know what Core version I have installed on that server, I have to add the -ConfigurationName parameter to the command.

Querying the Core edition version with $PSVersionTable

Querying the Core edition version with $PSVersionTable

Below, a little code will query the remote system for all possible versions and editions.

Invoke-Command -ComputerName srv2019 -ScriptBlock {$PSVersionTable.PSVersion}
try {
    Invoke-Command -ComputerName srv2019 -ConfigurationName "powershell.6" -ScriptBlock {$PSVersionTable.PSVersion} -ErrorAction stop
} catch { 
    Write-Host "PowerShell 6 is not installed" -ForegroundColor Yellow
}
try {  
    Invoke-Command -ComputerName srv2019 -ConfigurationName "powershell.7" -ScriptBlock {$PSVersionTable.PSVersion} -ErrorAction stop
} catch {  
    Write-Host "PowerShell 7 is not installed" -ForegroundColor Yellow
}

Retrieving all installed versions

Retrieving all installed versions

This method is by far the most accurate and easiest to use.

Checking the PowerShell version on Linux

Linux only supports the Core edition of PowerShell. In addition, updating the PowerShell installation is usually an in-place upgrade, so in the end, you can have only one PowerShell version installed.

As Linux does not have registry, there are three methods we can use—Get-Host, the $host variable, and the $PSVersionTable variable.

Getting the PowerShell version in Linux

Getting the PowerShell version in Linux

All of these methods work in Linux. Regarding the Get-Host method, I would expect the same behavior in Linux as in Windows, especially remotely, but I haven’t tested it.

Checking the PowerShell version on macOS

MacOS also only supports the Core edition of PowerShell. Just as in Linux, the new version is usually an in-place upgrade.

The methods in MacOS are also the same as in Linux—Get-Host, the $host variable, and the $PSVersionTable variable.

Subscribe to 4sysops newsletter!

Getting the PowerShell version in MacOS

Getting the PowerShell version in MacOS

Final words

This post gives you a comprehensive guide on how to check the installed PowerShell version and edition on Windows, Linux, and macOS. You have also learned how to distinguish between the two editions and how to check the information remotely.

avatar

Powershell logo 300x216 1

PowerShell — это мощный язык программирования и администрирования от компании Microsoft, каждый год он обрастает, все большим количество командлетов и функциональностей. По сути, это замена командной строке Windows. По умолчанию PowerShell установлен во всех версиях Windows, начиная с Windows 7 SP1 и Windows Server 2008 R2 SP1. Ниже рассмотрим как узнать какая версия у вас установлена.

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

img

host

PowerShell 1

img

$PSVersionTable.PSVersion

В итоге Windows 10 вывела мне версию 5.1 билд 19041.

PowerShell 2

img

Get-Host | Select-Object Version

PowerShell 3

img

(Get-Host).Version

или

img

$host.version

PowerShell 4

img

$host.version | Out-GridView

Благодаря этой команде выведется результат с версией установленной PowerShell в отдельном окне.

PowerShell 5

img

Write-Host (get-host).Version.Major (Get-Host).Version.Minor -Separator .

PowerShell 6

img

Get-Host

PowerShell 7

img

Get-Variable | where {$_.Name -Like ‘*version*’} | %{$_[0].Value}

PowerShell 8

Как проверить версию PowerShell через реестр Windows

Любые команды из оболочки или cmd, всего лишь обращаются к разделам реестра Windows и берет от туда нужную информацию. В реестре есть ветка:

img

HKEY_LOCAL_MACHINESOFTWAREMicrosoftPowerShell3 PowerShellEngine

Тут будет ключ реестра PowerShellVersion.

PowerShell 9

Прочитали: 163

Для определения версии Powershell есть с десяток вариантов. Обычно это нужно для проверки работы скриптов и команд. На примерах мы рассмотрим: как проверять версию PS, как работать с версией ниже и как узнать версию команд.

В зависимости от версии у вас сработает одна из команд:

host
# или
$PSVersionTable

версия powershell

Ниже можно посмотреть версии Powershell, с которыми уже идет операционная система и до какой версии мы можем обновить Powershell. В случае с Windows 7 версия Powershell 3.0:

Версии Powershell

Если вы хотите обновить оболочку PS, то вбейте в поиске, например, «windows management framework 5.1» и установите файл скаченный с сайта Microsoft.

Другая ситуация, когда мы не можем обновить Powershell. В таком случае у нас есть вариант запустить версию Powershell 2. Дело в том, что версии PS 3 и 4 обратно совместимы со скриптами версии 2. Для изменения версии вбейте в консоли:

powershell.exe -Version 2

Указанная версия будет работать до тех пор, пока сеанс открыт.

powershell какая версия

С версии PS 5.0 появилась возможность получения информации по версии командлета:

Get-Command Get-ChildItem

Версия команды Powershell

Не могу с уверенностью сказать, что эта цифра хоть как-то указывает на редакцию Powershell в которой этот командлет впервые появился. Возможно говориться о количестве выпусков с момента первого релиза, но например командлет Test-NetConnection появился в Powershell 4, но в PS 5.1 его версия 1.0:

Версия командлета Powershell

Противоположная ситуация со сторонними модулям, для примера модуль SQLServer имеет версию 21.

Если вы пишете исполняемый скрипт, то можете использовать следующий функционал, который определит какая версия Powershell установлена и в зависимости от этого выполнит разную работу с объектами:

$ps_version = (get-host).Version.Major
if ( $ps_version -eq "2" )
{
  # проверка на PowerShell v2
  write "Вы используете версию Powershell $ps_version... Скрипт сработает через ping!"
  write ""
  # Или какой-то командлет
  ping ya.ru
}
elseif ( $ps_version -eq "5" )
{
  # проверка на PowerShell v5
  write "Версия $ps_version подходит. Начало работы"
  write ""
  # команда для примера
  Test-NetConnection localhost
}
else
{ 
  write-host "Неизвестная ошибка"
  exit
}

Теги:

#powershell

  • Remove From My Forums
  • Question

  • Hi…all

    I installed SQL Server 2008 Dev edition on XP sp3.(It Installs WPS)

    I am very much new to PS..I started testing my Installation.

    For example, I typed Get-PS and press the Tab key , 
    the following cmdlets are appearing

    Get-PSDrive
    Get-PSProvider
    Get-PSSnapin

    But It suppose to show below list 

    ❑ Get-PSBreakpoint
    ❑ Get-PSCallStack
    ❑ Get-PSDrive
    ❑ Get-PSProvider
    ❑ Get-PSSession
    ❑ Get-PSSessionConfiguration
    ❑ Get-PSSnapin

    Why some other cmdlets are missing…Help me how to resolve and how check the Present version of WPS.

    Thanks in Advance


    SNIVAS

Answers

  • On Tue, 15-Dec-09 15:26:42 GMT, Karl Mitschke wrote:

    >To find the PowerShell version, in PowerShell, type the following command:Get-Host

    Actually — that’s not quite right — Get-Host just shows you the
    version of the host (i.e. of Console.Exe). To see the version of
    PowerShell, use the built in variable: $PSVersionTable.

    Thomas


    Thomas Lee — doctordns@gmail.com

    • Marked as answer by

      Tuesday, December 22, 2009 8:02 PM

    • Marked as answer by
      SNIVAS
      Tuesday, December 15, 2009 4:17 PM

UPD Метод опередления версии найденный мной оказался неверным. Вот правильный метод

Попытался узнать версию Powershell в свежеустановленном Windows Server 2008 R2 методом найденном в Интернет.

Powershell Version

Powershell Version

Безусловно радует то, что это вторая версия Powershell. Это вам и красивый отладчик, и Remotings, и многое другое. Но не могу не придраться к тому, что в финальной версии так и не убрали признак CTP выпуска.


Trackbacks & Pingbacks

  1. способ определения версии, на который вы ссылаетесь не совсем коректен (если не сказать совсем не корректен)

    Дело в том, что версия Host’а и версия PowerShell’а есть 2 большие разницы, хотя значения версий могут совпадать (и связаны между собой примерно так же, как версия MSWord — с версией Windows)

    Информация о версии содержится в переменной $PSVersionTable
    для того, чтобы отличить одну версию Posh от другой придется обратится к $PSVersionTable.buildversion и сравнивать поля Major, Minor, Build, Revision

    http://powershell.com/cs/blogs/tobias/archive/2010/01/21/are-you-using-the-correct-powershell-version.aspx

    | Ответить
    Опубликовано 12 years, 10 months ago

    • Вот уж действительно не углядел. Благодарю

      | Ответить
      Опубликовано 12 years, 8 months ago

Понравилась статья? Поделить с друзьями:
  • Как узнать версию драйвера чипсета windows 10
  • Как узнать включен ли гипертрейдинг windows 10
  • Как узнать версию powerpoint windows 10
  • Как узнать версию драйвера материнской платы windows 10
  • Как узнать включен ли брандмауэр windows