Shutting down a windows process from Mathematica - wolfram-mathematica

One can see there are list of process running in a Windows operating system just by opening the task manager. Now my question is if it is possible to shut down one such process from Mathematica front end.
I mean we need to write a script say to kill the "Process Tree" if the process is taking more than 95 percent of system RAM or it takes more than X minutes or seconds to complete. I dont know if that can be done from MMA but if possible it will come really handy in my project.
BR

I used a method to shut down a process in my reply here:
How can I make Mathematica kernel pause for an external file creation
taskkill /f /fi "imagename eq apame_win64.exe"
E.g. shutting down notepad:
ReadList["!taskkill /F /FI \"IMAGENAME eq notepad.exe\"", String]
This can be used in conjunction with tasklist to identify memory use:
ReadList["!tasklist", String]

You will probably want to use the Run function, and the TSKILL shell command.
TSKILL processid | processname [/SERVER:servername] [/ID:sessionid | /A] [/V]
processid Process ID for the process to be terminated.
processname Process name to be terminated.
/SERVER:servername Server containing processID (default is current).
/ID or /A must be specified when using processname
and /SERVER
/ID:sessionid End process running under the specified session.
/A End process running under ALL sessions.
/V Display information about actions being performed.

Related

How can I stop one instance via cmd of a process when several are running?

I start a program from a scilab script via the command line, start myprog.exe.
After the start my scilab script needs to keep going.
Now I want to stop exactly this instance of the process via the command line too, even if several instances of the same program are running.
Is that possible?
I know how to query via batch files whether a process of this program is running and then stop it, but I don't know how to get the exact allocation.
Is there something like a process id?
I use this to check if the process is running:
tasklist /fi "imagename eq ccx.exe" |find ":" > nul
if errorlevel 1 echo Program is running
if not errorlevel 1 echo Program is not running
Use the command tasklist to view all running tasks with their PID
then
Taskkill /PID 26356 /F
or
Taskkill /IM myprog.exe /F

Wait for a .bat file to close within a windows batch file

I need to create a windows batch file (*.bat) file that only runs its commands if certain processes (and batch files) are NOT running.
I have looked at a solution that works for processes (*.exe) here:
How to wait for a process to terminate to execute another process in batch file
I want to do something very similar, however, there is one difficulty: Batch files show up as "cmd.exe" in the "TASKLIST" command.
I want to check if a specific bat file is running, for example: "C:\mybatch.bat", and if it is, wait until it is closed.
Checking if a specific bat file mybatch.bat is running could be a tougher task than it could look at first sight.
Looking for a particular window title in tasklist /V as well as testing CommandLine property in wmic process where "name='cmd.exe'" get CommandLine might fail under some imaginable circumstance.
1st. Can you
add title ThisIsDistinguishingString command at beginning of the mybatch.bat and
remove all other title commands from mybatch.bat and
ensure that mybatch.bat does not call another batch script(s) containing a title command?
Then check errorlevel returned from find command as follows:
:testMybatch
tasklist /V /FI "imagename eq cmd.exe" | find "ThisIsDistinguishingString" > nul
if errorlevel 1 (
rem echo mybatch.bat batch not found
) else (
echo mybatch.bat is running %date% %time%
timeout /T 10 /NOBREAK >NUL 2>&1
goto :testMybatch
)
2nd. Otherwise, check if wmic Windows Management Instrumentation command output could help
wmic process where "name='cmd.exe'" get /value
Then you could detect mybatch.bat in its output narrowed to
wmic process where "name='cmd.exe'" get CommandLine, ProcessID
Note that wmic could return some Win32_Process class properties, particularly CommandLine, empty if a particular process was launched under another user account or elevated (run as administrator).
Elevated wmic returns all properties in full.
What you say happens by default.
To test, crate a new .bat file (let's say 1.bat) and put in it
calc
mspaint
Save and run it.
Calculator will start. You will notice that Paitbrush will launch only when you have closed calculator.

Monitor a start of process in windows, then execute something (stop another process/service)

can someone think of a solution for something like this? :
Program/script logic: It would constantly monitor the windows OS for a process starting within it (***1.exe) (I guess it could constantly run via task scheduler to do the constant monitoring?) , while it sees that ***1.exe is running, it would kill/end another process ***2.exe, and once ***1.exe would go away, it would no longer be stopping the ***2.exe process.
I think it could be either a bash script, powershell script, or a windows service?
Thanks!!!
You can use the Register-CimIndicationEvent cmdlet to register for events raised by Win32_ProcessStartTrace WMI class:
# Define which events to listen for
$NewProcessQuery = "SELECT ProcessId,ProcessName FROM Win32_ProcessStartTrace WHERE ProcessName LIKE '%1.exe'"
# Define the code to run every time a new process is created
$ProcessAction = {
# See if any instances of *2.exe processes are running
if(($TargetProcess = Get-CimInstance -ClassName Win32_Process -Filter "Name LIKE '%2.exe'"))
{
# Terminate them
$TargetProcess |Invoke-CimMethod -MethodName Terminate
}
}
# Register for the event
Register-CimIndicationEvent -Query $NewProcessQuery -SourceIdentifier ProcessCreated
So since the solution above was for only windows 2012 and up, I decided to try another solution. This should work for regular processes, but I'll have to try something else rather than %ERRORLEVEL% because the process I'm monitoring is originally an msi installer and seems like it returns and errorlevel of 1 all the time (running or not) while regular processes return 0 or 1 depending on the status. The process I'm ending starts back up automatically, that's the reason there's no start service command included in here, timeout was set to 62 seconds because the service starts back up automatically every 60 seconds, a /NOBREAK can be added if wanted to eliminate the possibility of user input starting it (if this would be ran without a task scheduler,etc.)
:loop_check
TIMEOUT /T 62
TASKLIST /FI "IMAGENAME eq process.exe" 2>NUL | find /I /N "process.exe">NUL
IF "%ERRORLEVEL%"=="0" (
GOTO stop_process2
) ELSE (
GOTO loop_check
)
:stop_process2
ECHO killing task
TASKKILL /F /IM process2.exe
GOTO loop_check
Read my previous reply/comment before this one for more clarity. This is the final solution that worked for me. A star(*) is included at the end of the 'BeginningOfApplicationName' because the installer/msi I'm detecting has sometimes different names based on it's version, so it finds/finishes the ending (wildcard). Since the name of the process I'm monitoring can have different names, I couldn't compare it to a static string, so I'm comparing it to INFO: , seems thats what windows (2008 and 2012!) both print out when a process is not found.
#ECHO OFF
SETLOCAL EnableExtensions
:loop_check
TIMEOUT /T 62
FOR /F %%x IN ('tasklist /NH /FI "IMAGENAME eq BeginningOfApplicationName*"') DO IF %%x == INFO: (
GOTO loop_check
) ELSE (
GOTO stop_process
)
:stop_process
TASKKILL /F /IM process.exe
GOTO loop_check

Calculate total running processes and return value in Batch

I am looking for a small little Batch file that counts total running processes and returns the value.
listing with tasklist and counting the .exe's with find
tasklist | find /i ".exe" /c
note that this excludes "System" and "System Idle Process" (are there more processes without an .exe?)
#echo off
tasklist | find /c "."
pause>nul

Any way to write a Windows .bat file to kill processes? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Every time I turn on my company-owned development machine, I have to kill 10+ processes using the Task Manager or any other process management app just to get decent performance out of my IDE. Yes, these are processes from programs that my company installs on my machine for security and compliance. What I'd like to do is have a .bat file or script of some kind with which I can kill the processes in question.
Does anybody know how to do this?
You can do this with 'taskkill'.
With the /IM parameter, you can specify image names.
Example:
taskkill /im somecorporateprocess.exe
You can also do this to 'force' kill:
Example:
taskkill /f /im somecorporateprocess.exe
Just add one line per process you want to kill, save it as a .bat file, and add in your startup directory. Problem solved!
If this is a legacy system, PsKill will do the same.
taskkill /f /im "devenv.exe"
this will forcibly kill the pid with the exe name "devenv.exe"
equivalent to -9 on the nix'y kill command
As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:
TSKILL processName
or
TSKILL PID
Have on mind that processName should not have the .exe suffix and is limited to 18 characters.
Another option is WMIC :
wmic Path win32_process Where "Caption Like 'MyProcess%.exe'" Call Terminate
wmic offer even more flexibility than taskkill with its SQL-like matchers .With wmic Path win32_process get you can see the available fileds you can filter (and % can be used as a wildcard).
I'm assuming as a developer, you have some degree of administrative control over your machine. If so, from the command line, run msconfig.exe. You can remove many processes from even starting, thereby eliminating the need to kill them with the above mentioned solutions.
Get Autoruns from Mark Russinovich, the Sysinternals guy that discovered the Sony Rootkit... Best software I've ever used for cleaning up things that get started automatically.
Download PSKill. Write a batch file that calls it for each process you want dead, passing in the name of the process for each.
Use Powershell! Built in cmdlets for managing processes. Examples here (hard way), here(built in) and here (more).
Please find the below logic where it works on the condition.
If we simply call taskkill /im applicationname.exe, it will kill only if this process is running. If this process is not running, it will throw an error.
So as to check before takskill is called, a check can be done to make sure execute taskkill will be executed only if the process is running, so that it won't throw error.
tasklist /fi "imagename eq applicationname.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "applicationname.exe"
Here I wrote an example command that you can paste in your cmd command line prompt and is written for chrome.exe.
FOR /F "tokens=2 delims= " %P IN ('tasklist /FO Table /M "chrome*" /NH') DO (TASKKILL /PID %P)
The for just takes all the PIDs listed on the below tasklist command and executes TASKKILL /PID on every PID
tasklist /FO Table /M "chrome*" /NH
If you use the for in a batch file just use %%P instead of %P

Resources