确定已安装的PowerShell版本

确定已安装的PowerShell版本

技术背景

在使用PowerShell进行系统管理和自动化任务时,了解当前安装的PowerShell版本至关重要。不同版本的PowerShell可能支持不同的功能和语法,因此在编写脚本或执行命令时,需要根据版本进行相应的调整。

实现步骤

1. 在PowerShell内部确定版本

  • 使用 $PSVersionTable.PSVersion:在PowerShell中,可直接使用该变量来获取引擎版本。若该变量不存在,则可认为引擎版本是 1.0
1
2
3
4
5
PS C:\> $PSVersionTable.PSVersion

Major Minor Build Revision
----- ----- ----- --------
4 0 -1 -1
  • 使用 Get-Host$PSVersionTable
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
get-host

Name : ConsoleHost
Version : 2.0
InstanceId : d730016e-2875-4b57-9cd6-d32c8b71e18a
UI : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture : en-GB
CurrentUICulture : en-US
PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace : System.Management.Automation.Runspaces.LocalRunspace

$PSVersionTable

Name Value
---- -----
CLRVersion 2.0.50727.4200
BuildVersion 6.0.6002.18111
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1

2. 从命令提示符外部确定版本

可通过以下命令在命令提示符中直接检查PowerShell版本:

1
powershell -Command "$PSVersionTable.PSVersion"

也可使用以下命令,该命令在CMD、PowerShell或Pwsh中都可使用:

1
powershell -command "(Get-Variable PSVersionTable -ValueOnly).PSVersion"

3. 通过注册表确定版本

  • 检查是否安装PowerShell:检查注册表中以下键值是否存在且值为 1
1
HKEY_LOCAL_MACHINE\Software\Microsoft\PowerShell\1\Install
  • 确定安装的PowerShell版本:检查以下注册表键值:
1
2
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine\PowerShellVersion
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine\PowerShellVersion

4. 确定PowerShell 7的版本

PowerShell 7安装后会在注册表中创建新的键值。可使用以下命令查询PowerShell 7的版本:

1
Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\PowerShellCore\InstalledVersions\*" -Name "SemanticVersion"

核心代码

函数获取PowerShell版本

1
2
3
function Get-PSVersion {
if (test-path variable:psversiontable) {$psversiontable.psversion} else {[version]"1.0.0.0"}
}

脚本中判断PowerShell版本并执行相应代码

1
2
3
4
5
6
7
8
if ($PSVersionTable.PSVersion.Major -eq 5) {
#Execute code available in PowerShell 5, like Compress
Write-Host "You are running PowerShell version 5"
}
else {
#Use a different process
Write-Host "This is version $PSVersionTable.PSVersion.Major"
}

批处理文件中根据PowerShell版本进行条件执行

1
2
3
4
5
6
powershell "exit $PSVersionTable.PSVersion.Major"
if %errorlevel% GEQ 5 (
echo Do some fancy stuff that only powershell v5 or higher supports
) else (
echo Functionality not support by current powershell version.
)

最佳实践

  • 在编写PowerShell脚本时,先检查PowerShell版本,根据版本选择合适的功能和语法,以确保脚本的兼容性。
  • 对于需要在不同版本PowerShell环境中运行的脚本,使用条件语句进行版本判断,避免因版本差异导致的错误。

常见问题

1. $Host.Version(Get-Host).Version 不可靠

这两个变量反映的是宿主应用程序的版本,而非PowerShell引擎的版本。例如PowerGUI、PowerShellPLUS等宿主应用程序会将宿主版本设置为其产品版本。

2. $PSVersionTable 在PowerShell 1.0中不存在

$PSVersionTable 变量不存在,则可认为当前使用的是PowerShell 1.0。


确定已安装的PowerShell版本
https://119291.xyz/posts/2025-05-12.determine-installed-powershell-version/
作者
ww
发布于
2025年5月12日
许可协议