我如何确定计算机上安装了哪种版本的PowerShell,以及是否确实安装了PowerShell?
当前回答
忘记此页面并永远不返回它的最简单方法是学习Get Variable:
Get-Variable | where {$_.Name -Like '*version*'} | %{$_[0].Value}
没有必要记住每个变量。仅获取变量就足够了(而且“版本应该有一些东西”)。
其他回答
以下cmdlet将返回PowerShell版本。
$PSVersionTable.PSVersion.Major
由于最有用的答案没有提到“如果存在”部分,我想我应该通过一个快速而肮脏的解决方案来解决这个问题。它依赖于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版本”的顶级搜索结果,因此我想提供一个基本示例,说明如何根据powershell版本在批处理文件中执行条件流
通用示例
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 "exit $PSVersionTable.PSVersion.Major"
if %errorlevel% GEQ 5 (
rem Unzip archive automatically
powershell Expand-Archive Compressed.zip
) else (
rem Make the user unzip, because lazy
echo Please unzip Compressed.zip prior to continuing...
pause
)
我制作了一个小批量脚本,可以确定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。
我需要检查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"
}
推荐文章
- Maven检查存储库中更新的依赖项
- 如何在PowerShell中获得本地主机名?
- PowerShell:如何将数组对象转换为PowerShell中的字符串?
- 从PowerShell ISE中的另一个PS1脚本调用PowerShell脚本PS1
- 如何运行一个PowerShell脚本而不显示窗口?
- PowerShell:仅为单个命令设置环境变量
- 是否有一种方法可以通过双击.ps1文件来使PowerShell脚本工作?
- Node -使用NODE_MODULE_VERSION 51根据不同的Node.js版本编译
- PowerShell等价于grep -f
- “Write-Host”,“Write-Output”,或“[console]::WriteLine”之间的区别是什么?
- Powershell相当于bash的&号(&),用于分叉/运行后台进程
- PowerShell脚本在机器上返回。net框架的版本?
- 如何在PowerShell中获得MD5校验和
- 如何在PowerShell格式化日期时间
- PowerShell和-contains操作符