简:我正在尝试在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
我怎样才能解决这个问题?
看起来你的ProcessBuilder
正在从你的cmd
论证中删除引号。您可以通过两种方式解决此问题:
转义引号:
public static String execute(String cmd) {
cmd = cmd.replace('"',"\\\"")
...
使用不需要引号的参数调用该命令:
Get-WmiObject -Class Win32_Printer -Filter { Default = True }