Jenkins – How to get the absolute path of a file (from workspace) in Jenkins pipeline script (in windows environment)

absolute-pathfilepathgroovyJenkinsjenkins-pipeline

How to get the absolute path of a file (from workspace) in Jenkins pipeline script (in windows environment)

File locations (The files are checked-out from Git and Jenkinsfile2.nprd will have the groovy pipeline script):

C:/Program Files (x86)/Jenkins/workspace/dev-my-api/my-data-api/my-data-api/pom.xml
C:/Program Files (x86)/Jenkins/workspace/dev-my-api/my-data-api/Jenkinsfile2.nprd

Script:

 stages {
        stage('Setup')  {
            steps {
                script {
                  pomPath = findFiles(glob: "**/pom.xml")[0].path
                  env.WORKSPACE = pwd()
                  pomDir = bat(script: "for %%F in ($pomPath) do set dirname=%%~dpF", returnStdout: true).trim()
                  echo "env.WORKSPACE:" + env.WORKSPACE
                  echo "pom file path:" + pomPath
                  echo "pom directory****:" + pomDir
                }
            }
        }
}

Output:

env.WORKSPACE:C:\Program Files (x86)\Jenkins\workspace\dev-my-api
pom file path:my-data-api\pom.xml
pom directory****:C:\Program Files (x86)\Jenkins\workspace\my-data-api>for %F in (my-data-api\pom.xml) do set dirname=%~dpF 

Requried path:

C:/Program Files (x86)/Jenkins/workspace/dev-my-api/my-data-api

How to get the above required path in Jenkins pipeline script without hard coding?

Best Answer

Try out the following (find pom.xml relative path & get the full path)

 def pomPath = findFiles(glob: "**/pom.xml")[0].path
 echo new File(env.WORKSPACE, pomPath).getParent() +"\pom.xml"
Related Topic