如何运行windows cmd命令"查询会话"在Java的processbuilder中?

时间:2015-10-15 12:40:30

标签: java cmd processbuilder

这就是我正在尝试的

ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "\"query && session\"");

但是我收到了错误:

'query' is not recognized as an internal or external command,
operable program or batch file.

我在这里做错了什么?

2 个答案:

答案 0 :(得分:3)

原因是您在64位Windows上运行32位Java VM。在这种情况下,%SystemRoot%\syswow64\cmd.exe将被执行而不是%SystemRoot%\system32\cmd.exe

小例子

public static void main(String[] args) throws Exception {
    for (String s : Arrays.asList("java.vm.name", "sun.arch.data.model")) {
        System.out.printf("%s=%s%n", s, System.getProperty(s));
    }
    ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", "query session");
    pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    pb.redirectError(ProcessBuilder.Redirect.INHERIT);
    pb.start();
}

在64位Windows上使用32位JVM输出

java.vm.name=Java HotSpot(TM) Client VM
sun.arch.data.model=32
'query' is not recognized as an internal or external command,
operable program or batch file.

在64位Windows上使用64位JVM输出

java.vm.name=Java HotSpot(TM) 64-Bit Server VM
sun.arch.data.model=64
 SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
 services                                    0  Disc
>console           .....                     1  Active

修改

%SystemRoot%\syswow64\cmd.exe不知道查询命令。

C:\Windows\SysWOW64>cmd
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Windows\SysWOW64>query
'query' is not recognized as an internal or external command,
operable program or batch file.

%SystemRoot%\system32\cmd.exe知道查询命令。

C:\Windows\System32>cmd
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Windows\System32>query
Invalid parameter(s)
QUERY { PROCESS | SESSION | TERMSERVER | USER }

答案 1 :(得分:1)

尝试以交互方式进行...这有用吗?

ProcessBuilder pb = new ProcessBuilder("cmd.exe");
pb.redirectErrorStream(true);
Process p = pb.start();
PrintWriter writer = new PrintWriter(p.getOutputStream());
writer.println("/c \"query && session\"");