How to Use bat Command in Jenkins Pipeline
In Jenkins Pipeline, use the
bat step to run Windows batch commands or scripts. Wrap your command string inside bat('your-command') within a pipeline or node block to execute it on Windows agents.Syntax
The bat step runs Windows batch commands in Jenkins Pipeline. It takes a string with the command to execute.
bat('command'): Runs the specified batch command.- Returns the command output as a string if assigned to a variable.
- Use inside
pipelineornodeblocks.
groovy
bat('your-command-here')Example
This example shows a Jenkins Declarative Pipeline running a simple batch command to list files in the current directory on a Windows agent.
groovy
pipeline {
agent any
stages {
stage('Run bat command') {
steps {
bat('dir')
}
}
}
}Output
Volume in drive C has no label.
Volume Serial Number is XXXX-XXXX
Directory of C:\path\to\workspace
01/01/2024 12:00 PM <DIR> .
01/01/2024 12:00 PM <DIR> ..
01/01/2024 12:00 PM 123 Jenkinsfile
1 File(s) 123 bytes
2 Dir(s) 100,000,000,000 bytes free
Common Pitfalls
Common mistakes when using bat in Jenkins Pipeline include:
- Running
baton non-Windows agents causes errors becausebatis Windows-specific. - Not quoting commands properly can cause syntax errors.
- Expecting
batto return output without assigning it to a variable.
Always ensure your Jenkins agent is Windows when using bat.
groovy
pipeline {
agent any
stages {
stage('Wrong usage') {
steps {
// This will fail on Linux agents
bat('echo Hello World')
}
}
}
}
// Correct usage with Windows agent:
pipeline {
agent { label 'windows' }
stages {
stage('Correct usage') {
steps {
bat('echo Hello World')
}
}
}
}Quick Reference
Tips for using bat in Jenkins Pipeline:
- Use
bat('command')to run Windows batch commands. - Assign output:
def output = bat(script: 'dir', returnStdout: true). - Use Windows agents only.
- Quote commands properly to avoid syntax errors.
Key Takeaways
Use the
bat step to run Windows batch commands in Jenkins Pipeline.Always run
bat on Windows agents to avoid errors.Assign
bat output to a variable with returnStdout: true if you need the command result.Quote commands properly inside
bat to prevent syntax issues.Use
bat inside pipeline or node blocks.