Home > Mobile >  Azure DevOps PowerShell Json to text file - Unexpected token ':' in expression or statemen
Azure DevOps PowerShell Json to text file - Unexpected token ':' in expression or statemen

Time:11-04

I have an azure devops pipeline that I'd like to write the content of a variable that holds json to a text file.

Here are two tasks from the pipeline:

- 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"'

The CmdLine task works ok and outputs the json, as seen below:

enter image description here

However, the PowerShell task gives the following error:

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

  • } else {
  • ~ Unexpected token '}' in expression or statement.
    • CategoryInfo : ParserError: (:) [], ParseException
    • FullyQualifiedErrorId : UnexpectedToken

Anyone see what I'm doing wrong?

CodePudding user response:

$(swaggerContent) is an Azure Pipelines variable, not a PowerShell variable. It's just a placeholder that contains the JSON.

So in the line

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

Think of what happens if you just replace $(swaggerContent) with some JSON. You get something like

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

Note that the JSON is completely unescaped. It's not a string, it's just random text inserted in the middle of the script.

Azure Pipelines treats non-secret variables as environment variables when running scripts, so you can try something along the lines of:

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