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


当前回答

由于最有用的答案没有提到“如果存在”部分,我想我应该通过一个快速而肮脏的解决方案来解决这个问题。它依赖于PowerShell位于路径环境变量中,这可能是您想要的。(由于我不知道,所以给顶部的答案打个小提示。)将其粘贴到文本文件中并命名

测试Powershell版本.cmd

或类似。

@echo off
echo Checking powershell version...
del "%temp%\PSVers.txt" 2>nul
powershell -command "[string]$PSVersionTable.PSVersion.Major +'.'+ [string]$PSVersionTable.PSVersion.Minor | Out-File ([string](cat env:\temp) + '\PSVers.txt')" 2>nul
if errorlevel 1 (
 echo Powershell is not installed. Please install it from download.Microsoft.com; thanks.
) else (
 echo You have installed Powershell version:
 type "%temp%\PSVers.txt"
 del "%temp%\PSVers.txt" 2>nul
)
timeout 15

其他回答

要检查是否安装了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    

我需要检查PowerShell的版本,然后运行相应的代码。我们的一些服务器运行v5,其他服务器运行v4。这意味着某些功能(如压缩)可能可用,也可能不可用。

这是我的解决方案:

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"
}

我在7.1.0版上尝试过,结果成功了:

$PSVersionTable | Select-Object PSVersion

输出

PSVersion
---------
7.1.0

但它在5.1版上不起作用,所以在7版以下的版本上更适用:

$PSVersionTable.PSVersion

输出

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      18362  1171

EDIT

从PowerShell 7.2.5开始,您现在可以执行以下操作:

pwsh -v

Or

pwsh --version

输出

PowerShell 7.2.5

我发现检查是否安装的最简单方法是:

运行命令提示符(“开始”、“运行”、“命令”、“确定”)键入powershell,然后单击return。然后,您应该得到PowerShell PS提示:

C:\Users\MyUser>powershell

Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.

PS C:\Users\MyUser>

然后,可以通过键入$PSVersionTable.PSVersion:

PS C:\Users\MyUser> $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      -1     -1

PS C:\Users\MyUser>

如果要返回到命令提示符,请键入exit(如果还要关闭命令提示符,则再次退出)。

要运行脚本,请参见http://ss64.com/ps/syntax-run.html.