Giancarlo
Giancarlo

Reputation: 125

How Can I Write a Batch File Where I Start one Program and When that Program Finishes or Closes, Start Another

For example:

@echo off
start C:\Windows\system32\dfrgui.exe /C

Wait for defragmentation to finish.

start C:\"Program Files (x86)"\CCleaner\CCleaner.exe /AUTO

Wait for CCleaner to finish.

start C:\Windows\system32\cleanmgr.exe /sagerun:1

and so on.. You get the point. How I can do this? Thanks.

Upvotes: 1

Views: 615

Answers (1)

ChrisProsser
ChrisProsser

Reputation: 13118

Start can take a command line argument /WAIT e.g.

@echo off
title Test cmd start

start /WAIT wait.cmd 5
start /WAIT cmd /k echo launched second command

pause

This simple example uses another script I have written (wait.cmd shown below) as the first command executed, as you will see if you test this with the /WAIT option specified the script allows the first command to finish before continuing:

@echo off
rem call with # of seconds to wait

set /a secs=%1
set /a ms=%secs%*1000
echo Process will wait for %secs% seconds and then continue...
ping 1.1.1.1 -n 1 -w %ms% > nul
echo.
exit

As a side note if you open a cmd session you can find out about the arguments that a command such as start accepts e.g.

enter image description here


Update following comment

So to adapt the commands you listed in your question to finish before starting the next command in the script you could use:

@echo off
start /WAIT C:\Windows\system32\dfrgui.exe /C
start /WAIT C:\"Program Files (x86)"\CCleaner\CCleaner.exe /AUTO
start /WAIT C:\Windows\system32\cleanmgr.exe /sagerun:1

Upvotes: 1

Related Questions