KETTLE 隐藏执行bat命令

转换(Ktr) / Design / Scripting / User defined Java class

// 可选导入(Kettle 已默认导入常用包,如 org.pentaho.di.*)
import java.io.*;
import org.pentaho.di.core.exception.*;
import org.pentaho.di.trans.step.*;

public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws Exception {
    // 🔹 处理第一行时执行批处理(仅一次)
    if (first) {
        first = false;

        // 1. 定义批处理文件路径和工作目录
        String batPath = "D:\\webapps\\xxx\\test.bat";
        String workDir = "D:\\webapps\\xxx";
        
        // 2. 记录执行信息
        logBasic("开始执行批处理: " + batPath);
        logBasic("工作目录: " + workDir);

        // 获取配置文件路径(从 Kettle 变量或硬编码)
        String ExcelFilePath = getVariable("ExcelFilePath", "");
        logBasic("ExcelFilePath: " +ExcelFilePath);
        
        try {
            // 3. 创建ProcessBuilder对象
            String httpsUrl = "https://xxx/xxx.xlsx";
            String saveUrl = "D:/webapps/xxx/file1.xlsx";
            String executeCmd = "-Command \"(New-Object System.Net.WebClient).DownloadFile('" + httpsUrl + "', '" + saveUrl + "')\"";
            String hiddenCmd = "powershell -WindowStyle Hidden " + executeCmd;// + " -Wait";
            ProcessBuilder pb = new ProcessBuilder("cmd", "/c", hiddenCmd);
            logBasic("hiddenCmd: " + hiddenCmd);

            // 4. 设置命令和参数(解决空格路径问题)
            //pb.command("cmd", "/c", "start", "\"KettleBatch\"", "/wait", "\"" + batPath + "\"");
            
            // 5. 设置工作目录
            pb.directory(new File(workDir));
            
            // 6. 启动进程
            Process process = pb.start();
            
            // 7. 读取并记录输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                logBasic("BAT输出: " + line);
            }
            reader.close();
            
            // 8. 等待执行完成
            int exitCode = process.waitFor();
            
            // 9. 记录执行结果
            if (exitCode == 0) {
                logBasic("批处理执行成功,退出码: " + exitCode);
            } else {
                logError("批处理执行失败,退出码: " + exitCode);
            }
        } catch (Exception e) {
            logError("执行批处理时出错: " + e.getMessage());
            throw e; // 抛出异常使转换失败
        }
    }

    // 🔹 处理输入行(如果有上游步骤,逐行处理)
    Object[] row = getRow(); // 获取一行数据
    if (row == null) { // 无更多数据时,结束处理
        setOutputDone();
        return false;
    }

    // 🔹 将行传递给下游步骤(保持数据流转)
    putRow(data.outputRowMeta, row); 

    return true;
}

 

Reference:

Kettle 连接 Oracle 使用手册 及 问题解决方案

posted @ 2025-07-18 17:12  Robot-Blog  阅读(23)  评论(0)    收藏  举报