1

I try to retrieve a string from a powershell script and use it in Jenkins file, in order to change the displayed version in SonarQube.

I started to implement functionality for taking the project version from package.json. Basically I give a Workspace directory as param and I ask for the full path if he finds a package.json in Workspace itself or in child folders. If the file is found, parse it and return version:

updateDisplayedVersionInSonar.ps1

param (
  [Parameter(Mandatory = $true)]
  [string]$Workspace
)
try{

    $packageFullPath = ""
    $pcgVersion = ""

    Get-ChildItem -Path ${Workspace} -Filter package.json
     -Recurse -ErrorAction SilentlyContinue -Force | % {$packageFullPath = $_.FullName}
    try { 

      Test-Path $packageFullPath -PathType leaf

      $json = Get-Content $packageFullPath | Out-String | ConvertFrom-Json

      if($json.PSobject.Properties.Name -contains "version"){       
        $pcgVersion =  $json.version
      }
      else{
        $pcgVersion = "unknown"
      }

      Write-Output $pcgVersion          
  }
  catch {
    Write-Output "There is no package.json file!"
  }
}
catch{
  $ErrorMessage = $_.Exception.Message
  write-host "An error has occured: ${ErrorMessage}"
  exit 1
}

Now I want to use the version returned from ps script in a Jenkins file:

stage('SonarQube Frontend') {
environment {
    sonarqubeScannerHome = tool name: 'SonarQube Scanner', type: hudson.plugins.sonar.SonarRunnerInstallation'
    sonarQubeId = 'SonarQubeServer'
    sonarProjectName = "\"SPACE ${REPOSITORY_NAME}\""
    sonarProjectKey = "${REPOSITORY_NAME}"
    testsPaths = 'app/myProject-ui/webapp/TEST/unit/utils'
    testExecutionReportPaths = 'app/myProject-ui/reports/sonar/TESTS-qunit.xml'
    javascriptLcovReportPaths = 'app/myProject-ui/reports/coverage/lcov.info'
}
steps {

    withSonarQubeEnv(env.sonarQubeId) {     
        withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: sonarQubeId, usernameVariable: 'SONAR_USER', passwordVariable: 'SONAR_PASSWORD']]) {   
            script{
                sonarProperties =  " -Dsonar.projectName=${env.sonarProjectName}" +
                    " -Dsonar.projectKey=${env.sonarProjectKey}" +   
                    " -Dsonar.login=${SONAR_USER}" +
                    " -Dsonar.password=${SONAR_PASSWORD}" +
                    " -Dsonar.sources=./" +  
                    " -Dsonar.exclusions=**/*.java"
                //some other conditions

                //this line will be executed and i will see in Jenkins Console output the version found in package.json
                powershell "powershell -File C:/Automation/updateDisplayedVersionInSonar.ps1 -Workspace '${env.WORKSPACE}/app'"

                //I try to make it as a variable, but it will print "echo version here - null -" :(
                pcgVersion = powershell "powershell -File C:/Automation/updateDisplayedVersionInSonar.ps1 -Workspace '${env.WORKSPACE}/app'" 
                echo "echo version here - ${pcgVersion} -"

                //I want to use it here in order to be displayed the correct version of the app in Sonar
                sonarProperties = sonarProperties + " -Dsonar.projectVersion= ${pcgVersion}" 
            }

        bat "${env.sonarqubeScannerHome}/bin/sonar-scanner" + " -Dsonar.host.url=${SONAR_HOST_URL}" + sonarProperties
        }   

    } 
}
} //end of SonarQube Frontend stage

I tried the solution from How to execute powershell script from jenkins by passing parameters but without any result.

I tried also to do this way:

version = powershell(returnStdout: true, script:'powershell -File C:/SCP/Automation/updateDisplayedVersionInSonar.ps1 -Workspace "${env.WORKSPACE}"')


version = powershell(returnStdout: true, script:'C:/SCP/Automation/updateDisplayedVersionInSonar.ps1 -Workspace "${env.WORKSPACE}"')

I found quite a lot of examples of how to use Jenkins variable in Powershell, but not vice versa :(

What I am doing wrong? It is possible to achieve this?

Thank you!

2
  • What is the error that you see? Try replacing single quotes with double quotes and removing env before WORKSPACE as in version = powershell(returnStdout: true, script:"C:/SCP/Automation/updateDisplayedVersionInSonar.ps1 -Workspace $WORKSPACE"). Commented Oct 16, 2019 at 14:16
  • You could use build-in jenkins utils to read a json file jenkins.io/doc/pipeline/steps/pipeline-utility-steps/… def props = readJSON file: 'app/package.json' props['version'] to get the version Commented Oct 16, 2019 at 14:25

1 Answer 1

1

You could use Jenkins Pipeline Utility instead.

def getPackageVersion() {
  def package = readJSON file: '${env.WORKSPACE}/app/package.json'
  echo package.version
  return package.version
}

Then you should be able to access it like this.

def pcgVersion = getPackageVersion()
Sign up to request clarification or add additional context in comments.

1 Comment

Hmm, i didn't think at doing this in groovy directly, but i'll try..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.