不使用CMD.EXE运行批处理命令

3

我想在C#应用程序中运行批处理命令。 通常,我会通过以下代码实现:

string command = "shutdown -s -t 120";
Process process = new Process();    
ProcessStartInfo startInfo = new ProcessStartInfo(); 
startInfo.WindowStyle = ProcessWindowStyle.Hidden;   
startInfo.FileName = "cmd.exe"; 
startInfo.Arguments = ("/c" + command); 
process.StartInfo = startInfo;   
process.Start();

然而,我正在为一个不允许使用CMD.EXE的网络构建该应用程序。我可以通过创建一个包含“COMMAND.COM”字符串的*.bat文件来访问命令提示符 - 然后我必须手动输入命令。上述代码将无法让我将字符串命令传递给批处理文件,只能传递给*.exe文件。有没有什么方法可以解决这个问题?

3
这个怎么样?https://dev59.com/7HVD5IYBdhLWcg3wDXJ3 直接运行关机命令。 - tire0011
2个回答

4
答案是完全绕过cmd,在这里不需要它,shutdown将成为一个独立的进程,因此直接运行即可:
Process.Start("shutdown","/s /t 120");

2

Shutdown不是批处理命令,而是系统可执行文件。您可以调用它来代替cmd:

C:\Windows>dir /s shutdown.exe
 Volume in drive C has no label.
 Volume Serial Number is 008A-AC5B

 Directory of C:\Windows\System32

30-10-2015  08:17            37.376 shutdown.exe
               1 File(s)         37.376 bytes

 Directory of C:\Windows\SysWOW64

30-10-2015  08:18            33.792 shutdown.exe
               1 File(s)         33.792 bytes

因此,您可以将当前的代码替换为:

Process process = new Process();    
ProcessStartInfo startInfo = new ProcessStartInfo(); 
startInfo.WindowStyle = ProcessWindowStyle.Hidden;   
startInfo.FileName = "shutdown.exe"; 
startInfo.Arguments = ("-s -t 120"); 
process.StartInfo = startInfo;   
process.Start();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接