ProcessBuilder 中的逃逸空间 [英] Escape space in ProcessBuilder

查看:83
本文介绍了ProcessBuilder 中的逃逸空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在 Eclipse 中执行以下代码:

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

但如果路径为 C:\\Users\\SendMailPS.ps1,我可以执行它.所以问题出在空格上,我该如何解决?

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?

我也这样试过

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

错误:

C:\Users\my :术语C:\Users\my"不被识别为cmdlet、函数、脚本文件或可运行程序的名称.检查名称的拼写,或者如果包含路径,请验证路径是否为更正并重试.

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.

推荐答案

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

您在这里实际做的是运行一个单行的 powershell 脚本,该脚本调用您的 SendMailPS 脚本.单行脚本受 powershell 的脚本解析影响,这会导致您的问题.

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

这明确告诉 Powershell 将指定文件作为脚本运行.

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.

这篇关于ProcessBuilder 中的逃逸空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆