我如何确定计算机上安装了哪种版本的PowerShell,以及是否确实安装了PowerShell?


当前回答

我会使用Get Host或$PSVersionTable。正如Andy Schneider所指出的,$PSVersionTable在版本1中不起作用;它在版本2中引入。

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

其他回答

要检查是否安装了PowerShell,请使用:

HKLM\Software\Microsoft\PowerShell\1 Install ( = 1 )

要检查是否安装了RC2或RTM,请使用:

HKLM\Software\Microsoft\PowerShell\1 PID (=89393-100-0001260-00301) -- For RC2
HKLM\Software\Microsoft\PowerShell\1 PID (=89393-100-0001260-04309) -- For RTM

资料来源:本网站。

您可以查看内置变量$psversiontable。如果它不存在,你就有V1。如果它确实存在,它将为您提供所需的所有信息。

1 >  $psversiontable

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

这是一个很老的问题,但仍然相关,只是问题的性质在2023年有所不同。找到版本很容易,但首先我们必须启动正确的可执行文件。为此,我们基本上回到了注册表中。

reg query "HKLM\SOFTWARE\Microsoft\PowerShell\1" /v Install >nul 2>&1
if %ERRORLEVEL% EQU 0 (
  :: Default to PowerShell 5 if both are installed
  set PSEXE=powershell
) else (
  set PSEXE=pwsh
)
echo Using %PSEXE%
%PSEXE% -ExecutionPolicy bypass -command "& { ... ; exit $LASTEXITCODE }"

通过检查环境变量可以获得其他提示,但我认为测试注册表中的“Windows”PowerShell是最安全的。

我制作了一个小批量脚本,可以确定PowerShell版本:

@echo off
for /f "tokens=2 delims=:" %%a in ('powershell -Command Get-Host ^| findstr /c:Version') do (echo %%a)

这只是使用Get-Host提取PowerShell的版本并搜索字符串version

当找到具有版本的行时,它使用for命令提取版本。在本例中,我们说定界符是一个冒号,然后搜索第一个冒号,这就是我的例子5.1.183627.52。

您可以通过完成以下检查来验证是否安装了Windows PowerShell版本:

单击开始,单击所有程序,单击附件,单击Windows PowerShell,然后单击Windows PowerShell。在Windows PowerShell控制台中,在命令提示符处键入以下命令,然后按ENTER键:获取主机|选择对象版本

您将看到如下输出:

Version
-------
3.0

http://www.myerrorsandmysolutions.com/how-to-verify-the-windows-powershell-version-installed/