Reading a value from a file in a windows batch script - windows

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?

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)

for /f %%G in (appid.txt) do (SET PID=%%G)
echo %PID%
taskkill etc here...
This might help !

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".

Related

I don't Understand how to exist task in batch script?

I have made a file named CHECKPRODUCT.CMD. but I have another file that runs at startup and it is named ACTIVATED.cmd. but I don't understand how to exists task ACTIVATED.cmd in CHECKPRODUCT.cmd. like I tried this examples :
if tasklist == "ACTIVATED.cmd" (
goto :1 ) else (
goto :2 )
but, it doesn't work!
can someone help me with that ?? I NEED help. really!
thank you so much!
You can use tasklist to check many facets of tasks running and the OLD school training was give your bat files a title for exactly this reason.
First always ensure (and I often forget) use Title in a bat or cmd that is likely to not exit quickly its useful for tasklist as here and on occasion taskkill /t or considered bad if you use /F. Try to use a unique name otherwise editing activate.cmd can show up in notepad and cmd
#echo off & title ACTIVATED
echo Running Activated
pause
You can use other status tests than "running" see tasklist /?
tasklist /FI "WindowTitle eq ACTIVATED" /FI "STATUS eq running" | Find /i "cmd"
REM bad find=2 not found=1 found at least once=0
if %errorlevel% == 0 (
echo true) else (
echo false)
pause
You may need to use ....ACTIVATED*" if you want to test for multiple entries etc.
If I understand your question correctly, then you're trying to determine if another batch file is still running from another.
You can do that by checking the command line strings of running cmd.exe processes, using the WMI command line utility.
#Echo Off
SetLocal EnableExtensions
Set "ScriptName=ACTIVATED.cmd"
%SystemRoot%\System32\wbem\WMIC.exe Process Where^
"Name='cmd.exe' And CommandLine Like '%%%ScriptName:_=[_]%%%'"^
Get ProcessId /Value 2>NUL | %SystemRoot%\System32\find.exe "=" 1>NUL^
|| GoTo :2
:1
Echo %ScriptName% is running.
Pause
GoTo :EOF
:2
Echo %ScriptName% is not running.
Pause
Note: Whilst you're free to modify the script name on line 4, please be aware that this would need additional work, should you decide to use file names containing [, ], ^, or % characters.

How to find out when a program was started and then closed via cmd batch file and then create a rem on program close

I want to keep this simple. I have a ACCESS DB batch file that I want to run from a trusted users computer, or via task scheduler. Batchrun.mdb runs its queries and then exits automatically. I'd like to know how we can tell when it actually closes -- if and when it does i'd like to add a rem line that says update complete or similar with the time. Thank you! I cannot find anything on this via google. The key is knowing that the program actually opened, and closed. I will remove the exit /b if i can get this to work correctly.
Batch file:
Start "" "E:\REDACTED\Batch Files\Batchrun.mdb"
Exit /b
For adding the REM within your code, you can do Echo Rem [%date% %time%] update complete>>"%~f0" - As posted by #LotPings - And can have the batch loop using tasklist to seach for your program. Upon terminating, it will end the loop and print the REM timestamp in your script and exit.
#ECHO OFF
#SETLOCAL EnableDelayedExpansion
Start "" "E:\REDACTED\Batch Files\Batchrun.mdb"
Echo Rem [%date% %time%] Application Opened>>"%~f0"
:ProcessLoop
tasklist /FI "IMAGENAME eq Batchrun.mdb" 2>NUL | find /I /N "Batchrun.mdb">NUL
if "%ERRORLEVEL%"=="0" (GOTO :ProcessLoop) ELSE (GOTO :Closed)
:Closed
Echo Rem [%date% %time%] Application Closed>>"%~f0"
Exit /b
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: LOG

How to run scheduled job

I am struggling to find a way to run a scheduled job that has a special datestamp into it's name.
The name always starts with "OS_HOUSEKEEP_", followed by the datestamp - e.g.
OS_HOUSEKEEP_2018022616171014980.job
Also, no other jobs having "OS_HOUSEKEEP_" in their names are present on the machine.
Could someone advise easiest way to target it and run it once with MS-DOS command(s)?
In addition, I thought to list the current jobs with the following command:
schtasks /query /v /fo LIST | findstr "OS_HOUSEKEEP_".
Unfortunately it only comes as a result and I am unable to cache it then to process it by sections (devided with space).
No other solutions has come to my mind..
for /f "tokens=2 delims=," %%a in ('schtasks /query /v /fo csv^|find "OS_HOUSEKEEP_"') do set "task=%%~a"
set "task=%task:~1%"
echo taskname is:%task%.
the tilde in %%~a removes the quotes, the second set command removes the first character.

Batch - Kill program if running, start it if it's not

I'm trying to make a toggle batch script for a process so that if it's running it gets killed and if it's not it is started. This is what I have:
tasklist /FI "IMAGENAME eq ProcessName.exe" 2>NUL | find /I /N "ProcessName.exe">NUL
set procopen = %ERRORLEVEL%
if "%procopen%"=="0" taskkill /im ProcessName.exe
if NOT "%procopen%"=="0" start "" ProcessName.exe
But everytime I run it, after the first if statement I receive the error:
"1"=="0") was unexpected at this time.
I also feel like there's a more efficient way to write this, but I'm not exactly sure how. Any help is appreciated!
More efficient would be to use conditional execution.
tasklist | find /i "application.exe" >NUL && (
taskkill /im "application.exe" /f
) || (
start "" application.exe
)
I think the reason your script is failing is because you've got spaces surrounding your equal sign in your set procopen line. You're basically setting a variable named procopenspace=spacenumeral, with the spaces included in both the variable name and the value. In the set command, spaces are treated as literal space characters, rather than as token delimiters. Now if you had done set /a, it probably would've worked (as set /a is more tolerant of spacing). Or if you had left the spaces out and set "procopen=%ERRORLEVEL%", that probably would've worked too. Here's an example cmd console session to demonstrate:
C:\Users\me>set procopen = 0
C:\Users\me>set "res=%procopen%"
C:\Users\me>set res
res=%procopen%
C:\Users\me>set "res=%procopen %"
C:\Users\me>set res
res= 0

Windows batch file : PID of last process?

I am launching a browser from batch file.
START "www.google.com"
I would like to know the PID of this browser window launched.
There can be many browser windows launched on a single machine. I need to find the PID of the process which was launched by my batch file only. I tried with WINDOWTITLE filter. But its not a good idea as titles may change in future. I am using Windows XP/7
Any help would be appreciated.
Thanks.
For what it worth (question is more than 2 years old) this code do the trick, just change variable according to default browser exe
set "browser=palemoon.exe"
tasklist /FI "imagename eq %browser%" /NH /FO csv > task-before.txt
start www.google.com
tasklist /FI "imagename eq %browser%" /NH /FO csv > task-after.txt
:: fc /L /LB1 test4-Before.txt test4-After.txt | find /I "%browser%"
for /f "delims=, tokens=2,*" %%A in ('"fc /L /LB1 task-before.txt task-after.txt | find /I "%browser%""') do set pid=%%A
SETLOCAL enabledelayedexpansion
pid=!pid:"=!
ENDLOCAL
echo pid is %pid%
This is just an idea, to get you maybe on the way
there is a command called Tasklist
there is a switch called filter /FI with lets you decide what filter parameters you want to output, f.e PID. Output this to a > 1.TXT
start your proces
recheck the watchlist and output to 2.TXT
Then you would have to get creative. COmpare 1 to 2,
maybe remove the processes in 1 from the 2.TXT
The remainig PID is what you wanted?
If you have some programming experience, you could create your own console application that accepts command-line parameters and passes them to the Win32 API CreateProcess() function. One of its output values is the spawned process ID, which your app could then return. Then just update your batch file to call your app instead of using START directly.
I'm trying to do the same thing. Though there must be some way of doing it, but all my Googling suggests not.
Check out robvanderwoude.com to see a list of 3rd party tools and examples. Also check out the full list of Sysinternal's process utilities here.
I've been looking at this for about 2 hours now and I think that there is a way to do this, but it requires some more insight on how windows handles iexplore.exe for PID...
I have a working version of a batch file I wrote that will get you what you want, BUT only if its the FIRST AND ONLY Internet Explorer Window open.
For some reason I can't get the PID to change when I open new browsers, but I can get results if there is no window open (obviously because there is no PID)
Anyhow, this is what I have... you should be able to run this on your system and it will tell you that there are no differences and it might actually produce results if your default browser is Firefox or Chrome or something... just need to make the changes to what I'm providing.
#echo off
IF EXIST c:\temp\pshell.txt del c:\temp\pshell.txt
IF EXIST C:\temp\PID1.txt del C:\temp\PID1.txt
IF EXIST C:\temp\PID2.txt del C:\temp\PID2.txt
IF EXIST C:\temp\PowerFormat.txt del C:\temp\PowerFormat.txt
powershell.exe Get-Process iexplore>C:\temp\pshell.txt
FOR /F "skip=3 tokens=7 delims= " %%1 IN ( c:\temp\pshell.txt ) DO #echo %%1>> C:\temp\PID1.txt
start "title" "www.google.com"
powershell.exe Get-Process iexplore>C:\temp\pshell.txt
FOR /F "skip=3 tokens=7 delims= " %%2 IN ( c:\temp\pshell.txt ) DO #echo %%2>> C:\temp\PID2.txt
FC /L c:\temp\pid1.txt c:\temp\pid2.txt> C:\temp\FileComparison.txt
FOR /F "tokens=7 delims=" %%3 IN (c:\temp\FileComparison.txt) DO #echo %%3>C:\temp\DiffPID.txt
FINDSTR "FC: no differences encountered" c:\temp\FileComparison.txt
IF '%ERRORLEVEL%'=='0' del C:\temp\FileComparison.txt & echo.No PID Found
IF NOT '%ERRORLEVEL%'=='0' type c:\temp\FileComparison.txt
pause
exit
Let me know if this helps...

Resources