Azure DevOps中PowerShell访问Build.SourcesDirectory报错及导航咨询
Azure DevOps流水线PowerShell脚本问题及解决
问题场景
在Azure DevOps流水线YAML中编写PowerShell脚本查看Build.SourcesDirectory下的所有文件时触发错误,同时在发布流水线中尝试导航到该目录也无法找到对应路径。
错误的PowerShell脚本
- task: PowerShell@2 - powershell: | Get-ChildItem $(Build.SourcesDirectory)
错误信息
Invalid file path '/home/vsts/work'. A path to a .ps1 file is required.
问题原因与解决方法
1. 构建流水线脚本格式修正
原脚本存在YAML语法错误:将PowerShell@2任务和脚本块拆分成了两个独立步骤,导致系统误将$(Build.SourcesDirectory)解析为需要执行的.ps1文件路径,触发报错。
正确的YAML写法:
- task: PowerShell@2 script: | Get-ChildItem $(Build.SourcesDirectory)
也可明确指定脚本类型(更清晰):
- task: PowerShell@2 inputs: targetType: 'inline' script: | Get-ChildItem $(Build.SourcesDirectory)
2. 发布流水线中访问工件路径
发布流水线中不存在Build.SourcesDirectory变量,该变量仅在构建流水线中有效(对应代码仓库拉取的源码目录)。发布流水线需先下载构建产出的工件,再通过以下路径访问:
$(System.ArtifactsDirectory):所有下载工件的根目录- 若需导航到具体工件目录,需先添加「下载工件任务」,之后通过
$(System.ArtifactsDirectory)/<工件名称>访问对应路径。
示例发布流水线YAML:
- task: DownloadPipelineArtifact@2 inputs: buildType: 'current' artifactName: 'MyBuildArtifact' targetPath: '$(System.ArtifactsDirectory)/MyBuildArtifact' - task: PowerShell@2 script: | # 导航到下载的工件目录 Set-Location $(System.ArtifactsDirectory)/MyBuildArtifact # 查看目录下文件 Get-ChildItem
内容的提问来源于stack exchange,提问作者ITHelpGuy
相关产品推荐
相关产品推荐

