如何用单条PowerShell命令提取程序ProductVersion至变量
没问题,这就帮你解决PowerShell提取纯版本号并存入变量的需求!
单条PowerShell命令提取版本号并存入变量
你当前的命令因为用了Format-List和findstr才会带出冗余文本,其实可以直接访问属性值跳过格式化步骤,拿到干净的版本号。
方法1:同时存变量+写入文件
这条命令会把版本号存入PowerShell变量,同时输出到控制台,还能写入文件(文件里只有纯版本号):
powershell -NoLogo -NoProfile -Command "$version = (Get-Item -Path 'c:\myapp.exe').VersionInfo.ProductVersion; Write-Output $version; $version | Out-File 'c:\version.txt' -Encoding UTF8"
- 直接访问
VersionInfo.ProductVersion属性,一步拿到纯版本号 $version变量可以在同一条命令里继续使用(比如做后续判断)- 文件里只会保留
1.6.7.0这种纯版本号,没有多余前缀
方法2:仅存入PowerShell变量(不输出文件)
如果只是需要把版本号存在PowerShell会话的变量里,简化成这条就行:
powershell -NoLogo -NoProfile -Command "$version = (Get-Item -Path 'c:\myapp.exe').VersionInfo.ProductVersion"
额外:从cmd调用并传入cmd变量
如果你是在cmd环境里调用PowerShell,想把版本号存入cmd的变量,可以用这个命令:
for /f "delims=" %%v in ('powershell -NoLogo -NoProfile -Command "(Get-Item -Path 'c:\myapp.exe').VersionInfo.ProductVersion"') do set "MYAPP_VERSION=%%v"
之后在cmd里用%MYAPP_VERSION%就能拿到纯版本号。
补充:允许运行脚本时的写法
你提到如果能运行脚本会用$mystr = (get-...),脚本里可以更简洁:
$appVersion = (Get-Item -Path 'c:\myapp.exe').VersionInfo.ProductVersion # 后续直接用变量操作,比如写入文件 $appVersion | Out-File 'c:\version.txt' -Encoding UTF8
内容的提问来源于stack exchange,提问作者Rob
相关产品推荐
相关产品推荐

