如何在Jenkins Pipeline中使用Groovy获取工作空间下所有文件夹名称
Jenkins Pipeline 读取工作区文件夹名称到数组的实现方案
方案1:兼容所有Agent节点(优先使用)
该方案通过Jenkins内置的shell/powershell步骤在对应Agent节点执行目录查询,不会出现跨节点文件读取错误的问题,适配Linux、macOS、Windows各类运行环境。
pipeline { agent any stages { stage('获取文件夹列表') { steps { script { def names = [] // Linux/macOS Agent 执行以下代码 String dirOutput = sh( script: 'ls -d */ | sed "s/\\///g"', returnStdout: true ).trim() if (dirOutput) { // 处理空目录场景 names = dirOutput.split('\n') } // Windows Agent 替换为以下powershell代码即可 // String dirOutput = powershell( // script: '(Get-ChildItem -Directory).Name', // returnStdout: true // ).trim() // if (dirOutput) { // names = dirOutput.split('\r?\n') // } // 打印验证结果 println names // 输出:[A, B, C, D] } } } } }
方案2:仅Master节点运行场景可用
如果Pipeline固定在Master节点执行,可直接使用Groovy原生文件API操作:
script { // 获取当前工作区绝对路径 String workspace = pwd() // 筛选所有文件夹并提取名称 def names = new File(workspace).listFiles() .findAll { file -> file.isDirectory() } .collect { dir -> dir.name } println names }
注意:该方案不可用于跨Agent的Pipeline场景,Groovy原生文件API默认只会读取Master节点的文件系统,无法获取Agent节点的工作区目录。
内容的提问来源于stack exchange,提问作者user1938143
相关产品推荐
相关产品推荐

