user3429531
user3429531

Reputation: 355

running windows powershell command in java

I am able to run this command in Windows PowerShell.

Add-Content -Path C:/Users/User/Desktop/sda.txt -Value "`nThis is the last line"

I tried to run the similar command via Java but it's not executing the command.

Runtime runtime = Runtime.getRuntime();
System.out.println("powershell Add-Content -Path C:/Users/User/Desktop/sda.txt -Value " + "\"`nThis is the last line\"");
runtime.exec("powershell Add-Content -Path C:/Users/User/Desktop/sda.txt -Value " + "\"`nThis is the last line\"");

Second attempt as suggested by aquaraga

Runtime runtime = Runtime.getRuntime();
Process proc;
System.out.println("powershell Add-Content -Path C:/Users/User/Desktop/sda.txt -Value " + "\"`nThis is the last line\"");
proc = runtime.exec("powershell Add-Content -Path C:/Users/User/Desktop/sda.txt -Value " + "\"`nThis is the last line\"");
try {
            proc.waitFor();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Upvotes: 1

Views: 770

Answers (1)

aquaraga
aquaraga

Reputation: 4168

Wrap the powershell command argument in a single quote:

proc = runtime.exec("powershell Add-Content -Path C:/Users/User/Desktop/sda.txt -Value " + "\"'`nThis is the last line'\"");

Upvotes: 1

Related Questions