寻求PowerShell命令更新.NET Core项目程序集版本或appsettings.json
用PowerShell实现类似SubWCRev的TFS版本号更新方案
一、更新.NET Core程序集版本(模板替换模式)
模仿SubWCRev的模板替换逻辑,先准备带占位符的模板文件,再用PowerShell替换为实际TFS版本号:
- 准备AssemblyInfo模板文件
创建AssemblyInfo.Template.cs,用$WCREV$作为版本号占位符:
using System.Reflection; [assembly: AssemblyVersion("$WCREV$")] [assembly: AssemblyFileVersion("$WCREV$")] [assembly: AssemblyInformationalVersion("$WCREV$-alpha")]
- PowerShell替换命令
假设已将读取到的TFS版本号存入变量$tfsVersion:
# 读取模板内容 $templateContent = Get-Content -Path ".\AssemblyInfo.Template.cs" -Raw # 替换占位符为实际TFS版本号 $updatedContent = $templateContent -replace '\$WCREV\$', $tfsVersion # 生成最终的AssemblyInfo.cs文件 $updatedContent | Set-Content -Path ".\Properties\AssemblyInfo.cs" -Encoding UTF8
如果使用Directory.Build.props统一管理版本,可同理创建Directory.Build.Template.props模板:
<Project> <PropertyGroup> <AssemblyVersion>$WCREV$</AssemblyVersion> <FileVersion>$WCREV$</FileVersion> <InformationalVersion>$WCREV$-release</InformationalVersion> </PropertyGroup> </Project>
替换命令与上述AssemblyInfo模板一致,只需修改文件路径。
二、更新appsettings.json中的版本配置
针对JSON配置文件,避免直接字符串替换出错,使用PowerShell的JSON序列化能力处理:
# 读取appsettings.json并转换为对象 $appSettings = Get-Content -Path ".\appsettings.json" -Raw | ConvertFrom-Json # 更新指定配置项 $appSettings.AssemblyVersion = $tfsVersion # 写回文件(-Depth参数防止嵌套结构被截断) $appSettings | ConvertTo-Json -Depth 10 | Set-Content -Path ".\appsettings.json" -Encoding UTF8
如果配置项是嵌套结构(如"Version": {"Assembly": "xxx"}),只需调整赋值路径:$appSettings.Version.Assembly = $tfsVersion。
三、完整整合流程示例
# 1. 读取TFS工作区版本号(替换为你实际的读取逻辑) $tfsVersion = "12345" # 2. 更新AssemblyInfo模板 $assemblyTemplatePath = ".\AssemblyInfo.Template.cs" $assemblyOutputPath = ".\Properties\AssemblyInfo.cs" if (Test-Path $assemblyTemplatePath) { $templateContent = Get-Content $assemblyTemplatePath -Raw $updatedContent = $templateContent -replace '\$WCREV\$', $tfsVersion $updatedContent | Set-Content $assemblyOutputPath -Encoding UTF8 Write-Host "程序集版本已更新至: $tfsVersion" } else { Write-Warning "未找到AssemblyInfo模板文件: $assemblyTemplatePath" } # 3. 更新appsettings.json $appSettingsPath = ".\appsettings.json" if (Test-Path $appSettingsPath) { $appSettings = Get-Content $appSettingsPath -Raw | ConvertFrom-Json $appSettings.AssemblyVersion = $tfsVersion $appSettings | ConvertTo-Json -Depth 10 | Set-Content $appSettingsPath -Encoding UTF8 Write-Host "appsettings.json中的版本号已更新至: $tfsVersion" } else { Write-Warning "未找到appsettings.json文件: $appSettingsPath" }
内容的提问来源于stack exchange,提问作者Perry
相关产品推荐
相关产品推荐

