【问题标题】:Can't get CMD Output无法获得 CMD 输出
【发布时间】:2017-06-04 01:05:47
【问题描述】:

这是我的代码:

private void CheckLastLogon(string computername)
{
    string cmd = $"/C query user /server:{computername}";
    System.Diagnostics.Process proc = new System.Diagnostics.Process();
    proc.StartInfo.FileName = "cmd.exe";
    proc.StartInfo.Arguments = cmd;
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.CreateNoWindow = true;
    proc.StartInfo.RedirectStandardOutput = true;
    proc.Start();

    string output = proc.StandardOutput.ReadToEnd();

    proc.WaitForExit();
}

output 总是string.Empty,我不知道为什么...(它在CMD 中工作)。

可能是我命令中/c 的原因?它终止到快吗?

我的错误在哪里?


更新 1: 重定向ErrorOutput 后,我得到了一些额外的信息。

我添加了错误输出,它说找不到命令“查询”

那么我的命令有什么问题?

在这里你看到它在 cmd 中工作:


更新 2:如果我从我的命令中删除 /c,它不会做任何事情。如果我破坏调试器,它会在proc.StandardOutput.ReadToEnd(); 等待

一段时间后我收到了ContextSwitchDeadlock ...

这有什么可怕的错误?

【问题讨论】:

  • 如果你删除/C然后呢?
  • 那么它不会以某种方式终止......
  • 试试 Filename C:\Windows\System32\query.exe Args user /server:{computername},其余的保持原样
  • 我可以在 FileExplorer 中找到query.exe,但不知何故我在proc.Start() 上得到了Win32Exception...
  • ShellExecute 真/假?

标签: c# cmd process arguments


【解决方案1】:

如果你正在寻找你需要做的错误:

proc.StartInfo.RedirectStandardError = true;

然后从proc.StandardError读取。

更新 1:

如果使用cmd 作为中间人不起作用。您可以尝试将C:\Windows\System32\query.exe 直接作为独立的.exe 运行。这避免了必须使用 cmd 以及这可能导致的所有问题。

所以你会看到类似的东西:

ProcessStartInfo procstart = new ProcessStartInfo
{
           FileName = @"C:\Windows\System32\query.exe",
           Arguments = $"user /server:{computername}",
           UseShellExecute = false,
           CreateNoWindow = true,
           RedirectStandardOutput = true,
           RedirectStandardError = true
};
Process proc = new Process{StartInfo = procStart};
proc.Start();
string[] output = proc.StandardOutput.ReadAllLines();

更新 2:

system32只能被x64程序访问,x32程序被重定向到syswow64。

如果您为x64仅构建,则以下代码有效:

        ProcessStartInfo procstart = new ProcessStartInfo
        {
            FileName = "query",
            Arguments = "$"user /server:{computername}"",
            UseShellExecute = false,
            CreateNoWindow = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true
        };
        Process proc = new Process {StartInfo = procstart};
        proc.Start();
        Console.WriteLine(proc.StandardOutput.ReadToEnd());
        Console.WriteLine(proc.StandardError.ReadToEnd());
        Console.Read();

TLDR:

如果您尝试使用cmd 命令,请不要使用cmd 作为中间人,只需将其放在StartInfo.FileName 中即可。如果该命令在 system32 中,请确保为 x64 构建。

【讨论】:

  • 我只是希望看到该机器的最后一次登录。由于它在 CMD 上工作,我希望这里没有错误...
  • 那么你的命令有问题,而不是你如何获得输出
  • 我想你想要 UseShellExecute = true 否则它正在寻找一个名为 .exe 的查询而不是 cmd 命令 query。
  • 一旦我启用ShellExecute,我就会得到InvalidOperationException,我之前尝试过。
  • @FelixD。我猜他的意思是C:\Windows\System32\query.exe 你还有问题吗?抱歉,我想我可能误读了您之前的评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-18
  • 2021-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多