简体   繁体   中英

Running batch commands with no CMD.EXE

I am trying to run batch commands in a C# application. Usually, I would do this through the following code:

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();

However, I am building said application for a network that doesn't allow CMD.EXE. I can gain access to the Command Prompt through making a *.bat file with the "COMMAND.COM" string in it - then I have to type in the commands manually. The above code will not allow me to pass string commands to a batch file, only an *.exe file. Is there any way around this?

答案是完全绕过cmd ,你不需要它, shutdown将是一个进程本身,所以直接运行它:

Process.Start("shutdown","/s /t 120");

Shutdown isn't a batch command, it's a system executable. You can call it instead of 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

So you can replace your current code with:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM