12

I'm trying to run a batchscript present inside the workspace of jenkins. I have written a groovy script as below to do this

stage('batchscript') {
   steps{
      bat 'start cmd.exe /c C:\\Program Files (x86)\\Jenkins\\workspace\\jenkins Project\\batchfile.bat'\
   }
}

when I build the job it should open a new command window and run my batch file in a new command prompt executing all the bat commands. The build is succesful but no command window opens up. Any suggestion will be helpfull

papanito
  • 2,349
  • 2
  • 32
  • 60
deepinside
  • 351
  • 1
  • 5
  • 15

3 Answers3

27

Jenkins is aimed to execute shell commands in background mode, not for interactive(UI) mode. When you run start cmd.exe /c c://some/app.exe a new cmd UI is opened and this will never happen in jenkins.

Single line

If you need to execute a simple batch commands with jenkins :

stage('build') {
      cmd_exec('echo "Buils starting..."')
      cmd_exec('echo "dir /a /b"')
}

def cmd_exec(command) {
    return bat(returnStdout: true, script: "${command}").trim()
}

Here a advanced example :

Multiline

steps {
  echo 'Deploy to staging environment'

  // Launch tomcat
  bat """
    cd c:\\qa\\bin
    dir /a /b
    startup
  """
  
  bat """
    cd c:\\qa\\bin
    startup
  """

  // Code to move WAR to Tomcat
  bat "xcopy /y c:\\webapp\\target\\webapp.war ..."
  bat "xcopy /y c:\\webapp\\target\\webapp.war ..."
}

Example:

Invoke batch file

If you need to execute a batch file with jenkins :

stage('build') {
  dir("build_folder"){
      bat "run_build_windows.bat"
  }
}

or

stage('build') {
  bat "c://some/folder/run_build_windows.bat"
}

Windows paths some time are bizarre :s . Anyway, linux is the best choice to host jenkins.

JRichardsz
  • 14,356
  • 6
  • 59
  • 94
0

Reference: https://thenucleargeeks.com/2020/11/24/how-to-run-batch-scripts-commands-in-jenkinsfile/

node {
        stage('Preparation') {
           //Preparations and checkout the code 
        }
        stage('Build') {
           //Build command     
        }
        stage('Post build action'){
     
       bat '''  ECHO Hello World  '''
    
        }
     }
Aditya Malviya
  • 1,907
  • 1
  • 20
  • 25
0

I used the accepted answer with other sources to come up with a better approach in my opinion.

pipeline {
  agent any

    stage("deploy") {
      steps {

        echo "Calling multi line batch command"
        bat '''
        call "C:\\path\\to\\batFile.bat"
        set myVar=exampleVar
        echo > Sometimes you want to keep environment variables set by the .bat script
        echo > so multiline script works best in this case: %myVar%
        '''
        
        echo "Calling single line batch command"
        bat "C:\\path\\to\\batFile.bat"

      }
    }
  }
}
Bersan
  • 1,032
  • 1
  • 17
  • 28