从控制台应用程序调用cmd.exe时查询会话不起作用

时间:2014-06-17 19:05:08

标签: cmd wow64

查询会话在使用任何CPU或X86目标平台时不起作用,但在使用X64平台时有效。

[TestMethod]
public void TestMethod()
{
    ProcessStartInfo info = new ProcessStartInfo("cmd.exe","/k query session");
    Process proc = new Process();
    proc.StartInfo = info;
    proc.Start();
}

有人可以解释为什么会这样吗?当我将其设置为默认处理器架构设置为X86的任何CPU时,是否有一种方法可以使其工作?

2 个答案:

答案 0 :(得分:1)

您的计算机有两个版本的cmd.exe:

  • C:\ Windows \ System32下\ cmd.exe的
  • C:\ WINDOWS \ SysWow64资料\ cmd.exe的

使用Any CPU或x86运行应用程序时,将调用syswow64版本。此版本的cmd.exe没有query命令:

c:\Windows\SysWOW64>cmd.exe
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.

要使其在任何CPU或x86中运行,请确保调用cmd.exe的system32版本

答案 1 :(得分:0)

使用pinvoke.net可以轻松克服此问题。这是解决方案

[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool Wow64DisableWow64FsRedirection(ref IntPtr ptr);

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool Wow64RevertWow64FsRedirection(IntPtr ptr);

[TestMethod]
public void TestMethod3()
{
    IntPtr ptr = new IntPtr();
    Wow64DisableWow64FsRedirection(ref ptr);
    ProcessStartInfo info = new ProcessStartInfo(@"cmd.exe", "/k query session");
    Process proc = new Process();
    proc.StartInfo = info;
    proc.Start();
    Wow64RevertWow64FsRedirection(ptr);
}

在任何CPU,X86和X64目标平台上都能完美运行

相关问题