PowerShell environment variable in Jenkins Pipeline gives `org.jenkinsci.plugins.workflow.cps.EnvActionImpl@1b69f5bb:VARIABLE_NAME`
The syntax forms $env:BRANCH_NAME
and the equivalent ${env:BRANCH_NAME}
are PowerShell constructs, which means that in order to pass them through to PowerShell in an interpolating Groovy string ("..."
), you must \
-escape the $
character to prevent Groovy from interpreting the construct up front:
powershell "dotnet sonarscanner begin ... /d:sonar.branch.name=\$env:BRANCH_NAME"
That said, given that your command contains no Groovy variables that need to be interpolated (it's safe and more robust to let PowerShell reference environment variables), you can simply use a literal Groovy string, '...'
, where $
chars. destined for PowerShell need no escaping:
powershell 'dotnet sonarscanner begin ... /d:sonar.branch.name=$env:BRANCH_NAME'
As for what you tried:
"... $env:BRANCH_NAME"
in an interpolating Groovy string causes Groovy to interpolate variable env
(since it is preceded by $
), and treat :BRANCH_NAME
as a literal.
Since env
refers to the object that contains all environment variables, what you're seeing is the (unhelpful) stringification of that object, which is the class name (org.jenkinsci.plugins.workflow.cps.EnvActionImpl
) followed by an instance-specific hash code (@54ee3a8
).
Using ${env.BRANCH_NAME}
would have worked - given that the value of environment variable BRANCH_NAME
can be accessed as a property of the env
object - but note that this means that Groovy interpolates the value up front and that PowerShell then only sees the resulting value.
In simple cases (environment-variable values without whitespace or special characters), "${env.BRANCH_NAME}"
(up-front interpolation by Groovy) and "\${env:BRANCH_NAME}"
(later interpretation by PowerShell) are interchangeable, but only the latter approach works robustly with all values.
Turns out specifying the environment variable this way works:
powershell "dotnet sonarscanner begin /k:project-key /d:sonar.branch.name=${env:BRANCH_NAME}"
You can also use a period instead of a colon (${env.BRANCH_NAME}
).