2

I need to run a powershell script in a function called by Jenkins. When calling this function, two other parameters/variables are included. This is a sample of my code:

        powershell '''
            $Headers = @{"ApiKey"="$env:myKey"}
            $jsonBody = @{
                varOne= '$env:params.varOne'
                varTwo = '$env:params.varTwo'} | ConvertTo-Json -Depth 10

            Invoke-RestMethod -Method Post -Uri "myUrl" -Headers $Headers -Body $jsonBody
        '''
    

This is throwing a 'Bad Response' error. Note that if I hard code the values that are in the variable, the script works. I also try to wrap the script with withEnv but I got the same issue:

    withEnv(["varOne=${params.varOne}, varTwo=${params.varTwo}"]) {
    powershell '''
        $Headers = @{"ApiKey"="$env:myKey"}
        $jsonBody = @{
            varOne= '$env:params.varOne'
            varTwo = '$env:params.varTwo'} | ConvertTo-Json -Depth 10

        Invoke-RestMethod -Method Post -Uri "myUrl" -Headers $Headers -Body $jsonBody
    '''
}

Finally, I know I could call these variables successfully if I was using double quote instead of single ones

powershell """
some ps1 script
"""

However, when I do that it says:

groovy.lang.MissingPropertyException: No such property: Headers

1 Answer 1

2

If you're going to template variables you need """ as I said in the question you deleted, but you need to escape the $ on non templated variables

powershell """
        \$Headers = @{"ApiKey"="$env:myKey"}
        \$jsonBody = @{
            varOne= '$env:params.varOne'
            varTwo = '$env:params.varTwo'} | ConvertTo-Json -Depth 10

        Invoke-RestMethod -Method Post -Uri "myUrl" -Headers \$Headers -Body \$jsonBody
    """
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.