【问题标题】:Azure DevOps PowerShell Json to text file - Unexpected token ':' in expression or statementAzure DevOps PowerShell Json 到文本文件 - 表达式或语句中出现意外的令牌 \':\'
【发布时间】:2022-11-04 04:12:49
【问题描述】:

我有一个 azure devops 管道,我想将保存 json 的变量的内容写入文本文件。

以下是管道中的两个任务:

- task: CmdLine@2
             displayName: 'echo swagger content'
             inputs:
               script: |
                 echo "print value of swaggerContent output variable set in get-swagger-from-azure.ps1"
                 echo $(swaggerContent)

           - task: PowerShell@2
             displayName: 'write swagger content to file'
             inputs:
              targetType: 'inline'
              script: $env:swaggerContent | Out-File "$(Pipeline.Workspace)/swagger-content.json"'

命令行任务处理并输出 json,如下所示:

但是,PowerShell 任务给出以下错误:

在 D:\a_temp\05c70744-c4cc-4322-99a0-98f55e41fbba.ps1:7 char:1

  • } 其他 {
  • ~ 表达式或语句中出现意外标记“}”。
    • CategoryInfo : ParserError: (:) [], ParseException
    • FullyQualifiedErrorId:UnexpectedToken

有人看到我做错了什么吗?

【问题讨论】:

  • 如果如你所说,内容已经保存 json 的变量,那么为什么在你的脚本中使用ConvertTo-Json
  • 嗨 Theo,那是我在猜测解决方案!没有 ConvertTo-Json 我得到了同样的错误

标签: json powershell azure-devops


【解决方案1】:

$(swaggerContent) 是 Azure Pipelines 变量,而不是 PowerShell 变量。它只是一个包含 JSON 的占位符。

所以在行

$(swaggerContent) | ConvertTo-Json | Out-File "$(Pipeline.Workspace)/swagger-content.json"

想想如果你只是用一些 JSON 替换 $(swaggerContent) 会发生什么。你得到类似的东西

{ "foo": "bar" } | ConvertTo-Json | Out-File "$(Pipeline.Workspace)/swagger-content.json"

请注意,JSON 是完全没有转义.它不是一个字符串,它只是插入脚本中间的随机文本。

Azure Pipelines 在运行脚本时将非机密变量视为环境变量,因此您可以尝试以下方式:

$env:swaggerContent | Out-File "$(Pipeline.Workspace)/swagger-content.json"

【讨论】:

  • 感谢您的回答,但给出了:在 D:_tempc70744-c4cc-4322-99a0-98f55e41fbba.ps1:7 char:1 + } else { + ~ Unexpected token '}' in expression or statement。 + CategoryInfo : ParserError: (:) [], ParseException + FullyQualifiedErrorId : UnexpectedToken 我在问题中提供了更新的细节
  • 啊 - 我错过了一个撇号 - 2 分钟......
猜你喜欢
  • 1970-01-01
  • 2018-05-04
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 2014-11-12
  • 1970-01-01
相关资源
最近更新 更多