Oplop98
Oplop98

Reputation: 230

Call parameters in Powershell script in Jenkins

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

Upvotes: 2

Views: 297

Answers (1)

tim_yates
tim_yates

Reputation: 171074

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

Upvotes: 2

Related Questions