Home > database >  PowerShell command not getting executed using java Process class. While all other commands are worki
PowerShell command not getting executed using java Process class. While all other commands are worki

Time:12-11

I am trying to execute below command using java Process class but it's not giving me any response or neither its effecting which it should do.

But when I am executing the command directly on PowerShell its working fine only it's not working using java code. I have tried other PowerShell commands, and all are working fine accept this one.

It's a command to disable indexing of a drive.

Output its only printing the command and in response of isAlive() method call it replies with false.

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

isAlive : false

There is nothing more in the code I am just calling this method from my main class that's it like classObject.disableIndexing("D")

Note I am executing the same using admin rights only. Please help.

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;
        
}

CodePudding user response:

The problem here is likely that | is interpreted by the default shell (eg. cmd.exe) before being passed to powershell.exe.

To work around this, use the -EncodedCommand command line switch to safely pass the command to 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;
}

CodePudding user response:

@g00se Even with InheritIo I am getting error. like below.

public String enableDisableIndexing (String driveLetter) {
    
            String returnVal="";
            String powerShellCommand = "Get-WmiObject -Class Win32_Volume -Filter \"DriveLetter='I:'\" | Set-WmiInstance -Arguments @{IndexingEnabled=$False} ";//| Out-Null
            try {
                byte[] powerShellBytes = powerShellCommand.getBytes(StandardCharsets.UTF_16LE);
                String encodedCmd = new String(Base64.getEncoder().encode(powerShellBytes));
                String command = "powershell.exe -EncodedCommand "   encodedCmd;
                ProcessBuilder pb =  new ProcessBuilder(command);
                pb = pb.inheritIO();
                pb.start();
            }catch(Exception e) {
                e.printStackTrace();
                logger.info(e.getMessage());
            }
            return returnVal;
            
        }

error what I am getting in eclipse is below

java.io.IOException: Cannot run program "powershell.exe -EncodedCommand RwBlAHQALQBXAG0AaQBPAGIAagBlAGMAdAAgAC0AQwBsAGEAcwBzACAAVwBpAG4AMwAyAF8AVgBvAGwAdQBtAGUAIAAtAEYAaQBsAHQAZQByACAAIgBEAHIAaQB2AGUATABlAHQAdABlAHIAPQAnAEkAOgAnACIAIAB8ACAAUwBlAHQALQBXAG0AaQBJAG4AcwB0AGEAbgBjAGUAIAAtAEEAcgBnAHUAbQBlAG4AdABzACAAQAB7AEkAbgBkAGUAeABpAG4AZwBFAG4AYQBiAGwAZQBkAD0AJABGAGEAbABzAGUAfQAgAA==": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at com.RepairMe.UtillityFiles.DiskUtilitty.enableDisableIndexing1(DiskUtilitty.java:152)
    at com.RepairMe.UtillityFiles.DiskUtilitty.main(DiskUtilitty.java:276)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    ... 3 more
  • Related