【问题标题】:PowerShell command not getting executed using java Process class. While all other commands are working finePowerShell 命令未使用 java Process 类执行。虽然所有其他命令都工作正常
【发布时间】:2022-12-09 21:02:21
【问题描述】:

我正在尝试使用 java Process 类执行以下命令,但它没有给我任何响应,也没有给我它应该做的效果。

但是当我直接在 PowerShell 上执行命令时,它工作正常,只是它不能使用 java 代码。我已经尝试过其他 PowerShell 命令,并且一切正常,请接受这个命令。

这是禁用驱动器索引的命令。

输出它只打印命令,并响应 isAlive() 方法调用,它以 false 回复。

命令:powershell.exe Get-WmiObject -Class Win32_Volume -Filter "DriveLetter='I:'" | Set-WmiInstance -Arguments @{IndexingEnabled=$False}

活着:假

代码中没有更多我只是从我的主类调用这个方法就像classObject.disableIndexing("D")

请注意,我仅使用管理员权限执行相同的操作。 请帮忙。

public String disableIndexing(String driveLetter) {
        
    String returnVal="";
    String command = "powershell.exe Get-WmiObject -Class Win32_Volume -Filter \"DriveLetter='"+driveLetter+":'\" | Set-WmiInstance -Arguments @{IndexingEnabled=$False} ";
    try {   
        System.out.println(command);
        Process p = Runtime.getRuntime().exec(command);
        p.waitFor();
        String line1="";
        String line="";
        BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((line1 = br.readLine()) != null) {
                    System.out.println(line1);
            if(!line1.isEmpty())
            System.err.println(line1);
        }
        System.out.println(p.isAlive());
        if(p.exitValue()==0) {
            returnVal="Indexing changed Successfully";
                }else {
            returnVal="Your Drive is Not Responding Try After Some Time";
            }
    }catch(Exception e) {
        e.printStackTrace();
            
    }
    return returnVal;
        
}

【问题讨论】:

    标签: java powershell


    【解决方案1】:

    这里的问题很可能是 | 在传递给 powershell.exe 之前由默认 shell(例如 cmd.exe)解释。

    要解决此问题,请使用 -EncodedCommand 命令行开关将命令安全地传递给 powershell.exe

    public String disableIndexing(String driveLetter) {
        String driveLetter = "D";
        String powerShellCommand = "Get-WmiObject -Class Win32_Volume -Filter "DriveLetter='" + driveLetter + ":'" | Set-WmiInstance -Arguments @{IndexingEnabled=$False}";
    
        // Base64-encode the UTF16LE representation of the command
        byte[] powerShellBytes = powerShellCommand.getBytes(StandardCharsets.UTF_16LE);
        String encodedCmd = new String(Base64.getEncoder().encode(powerShellBytes));
    
        String command = "powershell.exe -EncodedCommand " + encodedCmd;
    
        try {
            // proceed the same as before ...
        }
        catch (Exception e) {
            // ...
        }
    
        return returnVal;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-28
      • 2017-04-03
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-19
      • 2018-12-24
      • 1970-01-01
      相关资源
      最近更新 更多