You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PowerShell获取含修订号和内部版本号的程序集版本?

在PowerShell中获取.NET5+程序的完整AssemblyVersion

问题分析

你代码中通过typeof(Shell).Assembly.GetName().Version拿到的是AssemblyVersion,而FileVersionInfo返回的是FileVersion,两者在.NET5+ SDK项目中可能因为自动生成配置的冲突导致不一致;而AssemblyName.GetAssemblyName报错,大概率是因为程序是单文件发布(单文件exe是打包后的容器,并非直接可加载的程序集),或者依赖缺失。

解决方案

方案1:用dotnet CLI直接读取(推荐,支持单文件发布)

无需加载程序集,直接通过dotnet SDK命令获取:

# 获取单文件程序的AssemblyVersion
$versionOutput = dotnet single-file info "C:\path\to\myprogram.exe" | Select-String "Assembly version"
$fullVersion = $versionOutput -replace "Assembly version: ", ""

执行后$fullVersion会得到类似2.44.2342.3435的结果。

如果是非单文件发布,也可以用ildasm工具:

# 先安装dotnet-ildasm工具(仅需一次)
dotnet tool install -g dotnet-ildasm

# 提取AssemblyVersion
$versionLine = dotnet ildasm "C:\path\to\myprogram.exe" --text | Select-String "AssemblyVersion"
$fullVersion = [regex]::Match($versionLine, 'AssemblyVersion\("([^"]+)"\)').Groups[1].Value

方案2:PowerShell加载程序集(仅适用于非单文件发布)

如果程序依赖都在exe所在目录,可通过Assembly.LoadFrom加载并读取版本:

$filePath = "C:\path\to\myprogram.exe"
# 切换到exe目录解决依赖问题
Push-Location (Split-Path $filePath)
$assembly = [System.Reflection.Assembly]::LoadFrom($filePath)
$fullVersion = $assembly.GetName().Version.ToString()
Pop-Location

方案3:让FileVersionInfo返回完整版本

如果你希望FileVersionInfo也能拿到带修订号的版本,需要确保手动配置的AssemblyFileVersion生效:

  1. 打开项目的csproj文件,添加以下配置,关闭SDK自动生成AssemblyInfo:
<PropertyGroup>
  <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
  1. 重新编译发布程序后,执行以下命令即可获取完整版本:
[System.Diagnostics.FileVersionInfo]::GetVersionInfo("C:\path\to\myprogram.exe").FileVersion

内容的提问来源于stack exchange,提问作者Soleil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 11:42:53