java使用JPowerShell执行powershell脚本经常出现数据错乱

     java项目中使用JPowerShell去执行一些powershell的sdk脚本,因为有些脚本执行需要提前导包所以无法让每一个方法都单独开一个powershell进程,目前是一个类一个powershell进程,这样就导致了我执行一个接口执行脚本后jpowershell返回说执行完毕了,然后我再去执行另一接口执行powershell脚本结果返回的是上一次执行返回的数据,再重新执行一遍就好了。

    请问各路大神有没有办法在无法开多个进程让不同脚本执行共用一个powershell进程的情况下能正确返回数据或者jpowershell能正确判断确实已经执行完没有数据遗漏。ps:延长powershell的执行时长是没用的。

看一下这篇博客 https://www.cnblogs.com/fuhj02/archive/2010/11/29/1890704.html

 

望采纳,谢谢

没太看懂你为什么要每个方法单独开一个powershell。powershell支持一个会话执行多条命令。

powershell的executeCommand 方法是同步返回的,点击去看源码,其实底层是用了线程池来执行的,然后根据你传入的时间来等待结果,猜测你获取到的结果不对是因为你本身代码存在问题导致,检查是否共用了某些变量。

@Service
public class DSReciverForWebService {
    @Resource
    private PowerShell textPowerShell;
   

    public String configWebSite(String param) {
        return ExecutePowerShellScript.doScriptWithJsonAndPiecewise(textPowerShell, "text/text.ps1", param);
    }




public class ExecutePowerShellScript {
    public static String doScriptWithJsonAndPiecewise(PowerShell powerShell, String path, String params) {
        path = getAbsolutePath(path);
        String command = "$do = " + path + " " + params;
        executeScript(powerShell, command);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String res = executeScript(powerShell, "$do | convertTo-json -depth 3");
        return res;
    }

    public static String doScriptWithJson(PowerShell powerShell, String path, String params) {
        path = getAbsolutePath(path);
        String command = path + " " + params + " | convertTo-json -depth 3";
        String res = executeScript(powerShell, command);
        return res;
    }

    public static String doScriptWithJson(PowerShell powerShell, String path) {
        path = getAbsolutePath(path);
        String res = executeScript(powerShell, path + " | convertTo-json -depth 3");
        return res;
    }

    public static String doCommand(PowerShell powershell, String path, String params) {
        return executeScript(powershell, path + " " + params);
    }

    public static String doCommandWithJson(PowerShell powershell, String path, String params) {
        return executeScript(powershell, path + " " + params + " | convertTo-json -depth 3");
    }

    public static String doCommandWithJsonAndPiecewise(PowerShell powershell, String path, String params) {
        String command = "$do = " + path + " " + params;
        executeScript(powershell, command);
        String res = executeScript(powershell, "$do | convertTo-json -depth 3");
        return res;
    }