Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
When you delete jobs in Jenkins, the corresponding workspaces in the build slaves won't be deleted automatically. This Jenkins script will go to each slave and check if the jobs are already deleted in Jenkins master and delete the workspace.
import com.cloudbees.hudson.plugins.folder.Folder
import hudson.FilePath
import jenkins.model.Jenkins
def boolean isFolder(String name) {
def item = Jenkins.instance.getItemByFullName(name)
return item instanceof Folder
def deleteUnusedWorkspace(FilePath root, String path) {
root.list().each { child ->
String fullName = path +
if (isFolder(fullName)) {
deleteUnusedWorkspace(root.child(, "$fullName/")
} else {
if (Jenkins.instance.getItemByFullName(fullName) == null) {
println "Deleting: $fullName "
for (node in Jenkins.instance.nodes) {
println "Processing $node.displayName"
def workspaceRoot = node.rootPath.child("workspace");
deleteUnusedWorkspace(workspaceRoot, "")
Copy link

devops04cloud commented Aug 11, 2018

Hey from where do we run this script, and how to run. Im new to devops, plz help.


Copy link

oarmstrong commented Oct 23, 2018

Thanks a lot for this! 👍


Copy link

yafevin commented Feb 21, 2019

Hey from where do we run this script, and how to run. Im new to devops, plz help.
Run this script in "Script Console".


Copy link

SUDARSHANCHAUDHARI commented May 31, 2019

@devops04cloud and @tastewind,

Open Jenkins >> Manage Jenkins

then scroll down in the options list and look for "Script Console"


Hope this will help you!

Thank you


Copy link

kusumat commented Jun 4, 2019

Why isFolder is being considered instead of deleting directly if the path doesn't exist in jenkins master


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment