如何在Azure YAML Pipeline中用PowerShell存储并跨阶段传递变量
解决Azure Pipeline中获取EXE版本并跨阶段传递的问题
问题根源分析
- 首次PowerShell脚本错误:用单引号包裹变量赋值语句,PowerShell会将其视为纯文本字符串,不执行
Get-Item表达式,导致$fileVersion为空。 - VSO变量设置错误:直接将
Get-Item表达式写入VSO命令字符串,未用$()包裹进行求值,输出原始表达式而非实际版本号。 - 跨阶段变量引用错误:
stageDependencies中使用小写build,但实际作业名称为大写Build,导致无法正确读取输出变量。
修正后的关键步骤
1. 动态获取EXE版本并设置输出变量
在Build阶段替换手动注入版本的任务,改为自动读取EXE文件版本:
- task: PowerShell@2 displayName: 获取EXE版本 name: getVar inputs: targetType: 'inline' script: | $exePath = "TargetEngine.Aspen.Services.Internal.JobScheduler\bin\Release\net6.0\TargetEngine.Aspen.Services.Internal.JobScheduler.exe" $fileVersion = (Get-Item $exePath).VersionInfo.FileVersion Write-Host "##vso[task.setvariable variable=FileVersion;isOutput=true]$fileVersion" Write-Host "已获取EXE版本: $fileVersion"
2. 修正跨阶段变量引用
在Invoke阶段的作业中,修正stageDependencies的作业名称大小写:
variables: exeVersion: $[stageDependencies.BuildandCopy.Build.outputs['getVar.FileVersion']]
完整修正后的Pipeline代码
# Starter pipeline # Start with a minimal pipeline that you can customize to build and deploy your code. # Add steps that build, run tests, deploy, and more: # https://aka.ms/yaml trigger: branches: include: - develop - release - main variables: solution: "**/*.sln" buildPlatform: "Any CPU" buildConfiguration: "Release" stages: - stage: BuildandCopy pool: vmImage: windows-latest jobs: - job: Build steps: - task: NuGetToolInstaller@1 displayName: 安装NuGet工具 inputs: versionSpec: "6" - task: NuGetCommand@2 displayName: 还原解决方案包 inputs: restoreSolution: "$(solution)" - task: VSBuild@1 displayName: 构建解决方案 inputs: solution: "$(solution)" vsVersion: latest msbuildArgs: '/p:SkipInvalidConfigurations=true /p:DeployOnBuild=true /p:WebPublishMethod=FileSystem /p:publishUrl="$(build.artifactstagingdirectory)\\" /p:DeployDefaultTarget=WebPublish' platform: "$(buildPlatform)" configuration: "$(buildConfiguration)" - task: PowerShell@2 displayName: 获取EXE版本 name: getVar inputs: targetType: 'inline' script: | $exePath = "TargetEngine.Aspen.Services.Internal.JobScheduler\bin\Release\net6.0\TargetEngine.Aspen.Services.Internal.JobScheduler.exe" $fileVersion = (Get-Item $exePath).VersionInfo.FileVersion Write-Host "##vso[task.setvariable variable=FileVersion;isOutput=true]$fileVersion" Write-Host "已获取EXE版本: $fileVersion" - powershell: Write-Host "当前版本: $(getVar.FileVersion)" - task: PublishBuildArtifacts@1 displayName: "发布API产物" - stage: InvokeAzureFunction jobs: - job: Invoke variables: exeVersion: $[stageDependencies.BuildandCopy.Build.outputs['getVar.FileVersion']] pool: server steps: - task: AzureFunction@1 inputs: function: 'URL' key: 'mykey==' method: 'POST' queryParameters: 'Version=$(exeVersion)' waitForCompletion: 'false'
内容的提问来源于stack exchange,提问作者Zohaib Khan
相关产品推荐
相关产品推荐

