Escape space in ProcessBuilder

筅森魡賤 提交于 2019-12-13 19:53:10

问题


I am not able to execute the following code in Eclipse:

public static void main(String[] arg){
    String path="C:\\Users\\my dir\\SendMailPS.ps1";
    ProcessBuilder processBuilderObject
                = new ProcessBuilder("powershell",path);
    try {
        processBuilderObject.start();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

But I am able to execute it if path is as C:\\Users\\SendMailPS.ps1. So the problem is with spaces, how can I solve this?

Edit: I tried like this as well

public static void main(String[] arg){
    String path="C:\\Users\\my dir\\SendMailPS.ps1";
    try {
        Runtime.getRuntime().exec("powershell "+path);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

But no use. Then I tried directly from command prompt

>powershell
> C:\Users\SendMailPS.ps1

This gives me output. But following line gives me error

>powershell
> C:\Users\my dir\SendMailPS.ps1

error:

C:\Users\my : The term 'C:\Users\my' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.


回答1:


String path="C:\\Users\\my dir\\SendMailPS.ps1";
ProcessBuilder processBuilderObject
            = new ProcessBuilder("powershell",path);

What you're actually doing here is to run a one-line powershell script which invokes your SendMailPS script. The one-line script is subject to powershell's script parsing, which is causing your problem.

Try running your script this way:

String path="C:\\Users\\my dir\\SendMailPS.ps1";
ProcessBuilder processBuilderObject
            = new ProcessBuilder("powershell", "-File", path);

This explicitly tells Powershell to run the specified file as a script.

Do not use string contatenation here:

// Don't do this
ProcessBuilder processBuilderObject
            = new ProcessBuilder("powershell -File " + path); // Don't do this
// Don't do this

Trying to run it this way will give you more trouble.



来源:https://stackoverflow.com/questions/19092285/escape-space-in-processbuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!