Sam Naughton B
Sam Naughton B

Reputation: 79

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?

Upvotes: 3

Views: 838

Answers (2)

jessehouwing
jessehouwing

Reputation: 114857

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

Upvotes: 2

user1017882
user1017882

Reputation:

The answer is to bypass cmd altogether, you don't need it here, shutdown will be a process itself, so just run it directly:

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

Upvotes: 4

Related Questions