0

In my situation, I am looking for a solution wherein a specific task gets executed from batch file.

Upon executing the same batch file the task/ processid which gets started by batch file previously should only get kill.

Currently with the command

taskkill /f /im "notepad.exe"
powershell.exe Start-Process notepad.exe

All the instances of notepad gets close which were opened by user/ any other process. however, I specifically want this batch file to close the PID which get created by it and close the same PID in case we run this batch file again.

May be with this requirement batch file should write a file with the ProcessName and its PID. and for every execution of batch file it should look for process ID mentioned there and close it if already running and open a new instance and update the file where the PID is being stored.

Any help will be appreciated. Thanks

ayush varshney
  • 517
  • 7
  • 20
  • somewhere i found "powershell.exe Start-Process notepad.exe -PassThru " which returns the PID too however i dont have much exposure of powershell or batchfile hence unable to proceed further. – ayush varshney Jan 29 '19 at 08:59
  • I believe this will be quite tedious with cmd batch in case if multiple processes with the same name are running. Consider to use some other language: Powershell, VBScript. – montonero Jan 29 '19 at 09:10
  • @montonero: would be grateful to you if you can provide some direction with Powershell too? – ayush varshney Jan 29 '19 at 09:13
  • 1
    You'll need to [get process id](https://stackoverflow.com/questions/4762982/powershell-get-process-id-of-called-application) and [kill it](https://ss64.com/ps/stop-process.html) – montonero Jan 29 '19 at 09:18
  • @montonero: Not really helpful for me as i am not aware of PowerShell programming. So in this case let me learn the powershell... – ayush varshney Jan 29 '19 at 09:29

1 Answers1

1

Although I do not recommend it and see it as a total overkill - a solution for cmd:

for /f "usebackq" %%p in (`powershell.exe -nologo -c "(start-process notepad.exe -passthru).id"`) do set pid=%%p
montonero
  • 1,363
  • 10
  • 16