C# 向 CMD 发送服务器查询并读取输出

C# Sending a Server QUERY to CMD and Reading the Output

更新 - 我的代码现在看起来像这样,文件 test.txt 是在 运行ning 之后生成的,但是文件是空的,所以我假设命令没有被发送到CMD 正确:

    static void command()
    {
        string cmd = "/c QUERY session >C:/test.txt";

        Process proc = new Process();

        proc.StartInfo.LoadUserProfile = true;

        proc.StartInfo.FileName = "cmd.exe";
        proc.StartInfo.Arguments = cmd;

        proc.Start();
        proc.WaitForExit();    
    }

谁能帮我想办法调试这个? Visual Studio 没有显示任何错误,因此很难判断发生了什么。

非常感谢任何帮助!


在 StackExchange 上看了一圈之后,我得到了以下用于打开命令提示符和发送命令的代码:

        string cmd = "/c QUERY user /SERVER: servername.goes.here";
        Process proc = new Process();
        proc.StartInfo.FileName = "cmd.exe";
        proc.StartInfo.Arguments = cmd;
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.RedirectStandardOutput = true;
        proc.Start();

        string output = proc.StandardOutput.ReadToEnd();

        MessageBox.Show(output);

        proc.WaitForExit();

当用简单的“notepad.exe”替换服务器查询时,CMD window 在 运行ning 时打开,notepad.exe 也是如此。

但是,当发送服务器查询时(这是为了检查哪些用户正在使用特定的 Citrix 服务器),我在 CMD 中看到了这条消息:

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

当我在 CMD 中手动输入查询时,系统会显示当前登录到该特定服务器的所有用户的列表。

我希望程序 运行 SERVER 查询,并将输出发送到消息 window,这样我就知道它已经工作了。

非常感谢任何帮助!

非常感谢

我还注意到,当从 cmd 字符串中删除 /c 时,我在 CMD 中没有看到查询错误,但是在这里或消息框中都没有看到任何输出

参数的“/c”部分仅表示 运行 后续代码。否则它不会执行您提供给它的代码。您看到的错误消息意味着当前环境无法找到 QUERY 程序。对于 "see" 程序的命令行,它必须是 OS PATH 环境变量的一部分,或者它必须位于当前工作目录中。您可以通过执行CD命令(Change Directory)将当前工作目录更改为包含QUERY.exe程序的目录。

您可以通过在各个语句之间使用“&”将各个命令传送到同一个 /c 开关。

cmd.exe /c CD "PATH TO TOOLS FOLDER" & QUERY user /SERVER: servername.goes.here

另一种方法是提供 QUERY.exe 程序的完整路径。

cmd.exe /c "C:\Program Files\Example\Tools\bin\QUERY.exe" user /SERVER: servername.goes.here

Read more about the cmd line switches