ProcessBuilder从powershell中的命令中删除“

问题描述 投票:2回答:1

简:我正在尝试在ProcessBuilder中运行命令:

public static String execute(String cmd) {
    System.out.println(cmd);
    ProcessBuilder builder = new ProcessBuilder("powershell.exe", cmd);
    StringBuilder fullStatus = new StringBuilder();
    String line = null;
    Process reg;
    builder.redirectErrorStream(true);
    try {
        reg = builder.start();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(reg.getInputStream()));
        while((line = bufferedReader.readLine()) != null) {
          fullStatus.append(line).append("\n");
        }
        reg.destroy();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return fullStatus.toString();
}

如果我执行以下命令:

Get-WmiObject -Query " SELECT * FROM Win32_Printer WHERE Default=$true"

它忽略了“在我的文件中。

Get-WmiObject:未找到接受“*”参数的位置参数。在行:1个字符:1 + Get-WmiObject -Query SELECT * FROM Win32_Printer WHERE默认= $ true + ~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo:InvalidArgument :( :) [Get-WmiObject],ParameterBindingException + FullyQualifiedErrorId:PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetWmiObjectCommand

我怎样才能解决这个问题?

java powershell
1个回答
1
投票

看起来你的ProcessBuilder正在从你的cmd论证中删除引号。您可以通过两种方式解决此问题:

转义引号:

public static String execute(String cmd) {
    cmd = cmd.replace('"',"\\\"")
    ...

使用不需要引号的参数调用该命令:

Get-WmiObject -Class Win32_Printer -Filter { Default = True }
© www.soinside.com 2019 - 2024. All rights reserved.