简体   繁体   中英

Exit command prompt after processing in a console application

I have the following command to run a task from scheduler which is a console application:

  ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = "cmd.exe";
            psi.Arguments = string.Format("/K SCHTASKS.EXE /Change /TN \"{0}\" /DISABLE", this.FullTaskName);
            Process.Start(psi);

Now I want to close the command prompt after executing the task. I tried,

  Environment.Exit(0);

but this termiantes the process and doesnot close the command prompt opened. I need to Exit the command prompt after running the task.

Assuming you do net to invoke SCHTASKS.EXE using cmd.exe you can do the following

ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = "cmd.exe";
        psi.Arguments = string.Format("/K SCHTASKS.EXE /Change /TN \"{0}\" /DISABLE & exit", this.FullTaskName);
        Process.Start(psi);

Please note the addition of & exit . & allows you to concatenate multiple commands to be executed in sequence.

When you use /k switch, you are asking the Command Prompt window to stay open. Use /c instead:

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "cmd.exe";
psi.Arguments = string.Format("/C SCHTASKS.EXE /Change /TN \"{0}\" /DISABLE", this.FullTaskName);
Process.Start(psi);

But why call cmd.exe anyway? Call SchTasks.exe directly.

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