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

Azure DevOps Pipeline中PowerShell读取JSON文件报错求助

解决Azure DevOps Pipeline中PowerShell脚本无法读取同目录JSON文件的问题

问题原因

你的脚本使用$pwd.Path获取当前工作目录,但在Azure DevOps Pipeline环境中,当前工作目录可能和脚本所在目录不一致;或者JSON文件未被正确检出到流水线工作目录中。

解决方案

1. 修正脚本中目录获取逻辑(推荐)

使用PowerShell内置变量$PSScriptRoot替代$pwd.Path,这个变量会直接返回当前运行的脚本文件所在的目录,避免工作目录差异导致的路径错误:

修改脚本代码:

# 获取当前脚本所在的目录,替代原有的$pwd.Path
$CurrentFolder = $PSScriptRoot
$Some_JSON_File = Join-Path $CurrentFolder 'SomeFile.json'
$JSON_Content = Get-Content $Some_JSON_File | ConvertFrom-Json
...

2. 确保流水线执行脚本时处于正确的工作目录

可以通过两种方式指定工作目录:

方式一:在流水线任务中设置workingDirectory

修改流水线步骤,明确指定脚本所在的目录($(Build.SourcesDirectory)是Azure DevOps内置变量,代表代码检出后的根目录):

steps:
  - checkout: self
  - task: PowerShell@2
    displayName: 'Powershell task'
    inputs:
      targetType: 'inline'
      script: '.\replace_placeholders.ps1'
      workingDirectory: '$(Build.SourcesDirectory)'

方式二:在执行脚本前切换目录

在inline脚本中先切换到代码根目录,再执行脚本:

steps:
  - checkout: self
  - task: PowerShell@2
    displayName: 'Powershell task'
    inputs:
      targetType: 'inline'
      script: |
        cd $(Build.SourcesDirectory)
        .\replace_placeholders.ps1

3. 排查文件是否被正确检出

如果以上方法无效,添加一个目录检查步骤,确认JSON文件是否存在于流水线工作目录中:

steps:
  - checkout: self
  - task: PowerShell@2
    displayName: 'Verify directory contents'
    inputs:
      targetType: 'inline'
      script: |
        # 列出代码根目录下的所有文件和文件夹
        dir $(Build.SourcesDirectory)
  - task: PowerShell@2
    displayName: 'Powershell task'
    inputs:
      targetType: 'inline'
      script: '.\replace_placeholders.ps1'

如果输出中没有SomeFile.json,需要检查:

  • 该文件是否已提交到代码库
  • 代码库的.gitignore或.tfignore等规则是否排除了该文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 14:05:22