10

I'm trying to read a value from a file and use it in a subsequent command.

I have a file called AppServer.pid which contains the process id of my app server (just the number, it's not a properties file or anything like that).

The app server is hanging, so I want to take this value and pass it to the kill command. So my script will be something like

SET VALUE_FROM_FILE=AppServer.pid # or something
taskkill /pid %VALUE_FROM_FILE% /f

Is there a convenient way to do this in Windows scripting?

Harry Lime
  • 29,476
  • 4
  • 31
  • 37

3 Answers3

17

This works:

SET /P VALUE_FROM_FILE= < AppServer.pid
taskkill /pid %VALUE_FROM_FILE% /f

The /P parameter used with SET allows you to set the value of a parameter using input from the user (or in this case, input from a file)

Cocowalla
  • 13,822
  • 6
  • 66
  • 112
  • Thanks. This is probably the more straightforward solution. – Harry Lime Nov 18 '08 at 11:15
  • if you launch it several times, It would take previous value but not current one. That how it works for me. – ses May 14 '14 at 15:59
  • @ses I have the same behaviour here. That's annoying because it seems to be behind time. It reads the content of a former version of the file. Even when called twice in the same script. Can't use that. PS: When called the first time, it reads nothing. This definitely is not the correct answer. – ygoe Jul 11 '20 at 16:22
1
for /f %%G in (appid.txt) do (SET PID=%%G)
echo %PID%
taskkill etc here... 

This might help !

RuntimeException
  • 1,593
  • 2
  • 22
  • 31
  • This suffers from the same issue as the accepted answer. It reads the contents of the file as it was when the script was last called. Not useful. – ygoe Jul 11 '20 at 16:26
  • I cannot know what is wrong without seeing the error message (if any). But try the following. 1. Try running it again in another cmd window after the previous run. Each run in new window. 2. Avoid leading or trailing blank lines in the file. 3. use setlocal and endlocal. – RuntimeException Jul 15 '20 at 17:44
1

If you know the name of the process, as returned from the command tasklist, then you can run taskkill with a filter on the process name, i.e. /FI IMAGENAME eq %process_name%.

For example, to kill all of the processes named nginx.exe run:

    taskkill /F /FI "IMAGENAME eq nginx.exe"

Which "reads in English": kill all tasks (forcefully if needed via /F) that match the filter /FI "IMAGENAME equals nginx.exe".

isapir
  • 21,295
  • 13
  • 115
  • 116