Find a Windows process based on its description, using CMD - windows

I get two results when I run this:
tasklist /FI "imagename eq PROCESS.exe"
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
PROCESS.exe 2760 Console 1 8,156 K
PROCESS.exe 20160 Console 1 9,060 K
But I only want to kill ONE of them...
If I open up the Task Manager, I can see that each of my processes have different descriptions.
So all I need to do, is somehow filter by process description.
Can anyone help, please?
Thank you!

Use the following to distinguish the processes according to their own process ID and their parent process ID:
wmic process get processid,parentprocessid,executablepath | find "PROCESS"
This way, you can find the process ID to kill.
wmic grants access to additional process properties.
Use wmic process get /? to find out what is available.
Another potentially helpful tool is PsList of Microsoft/Sysinternals.

If you want to filter your process list by the window title, just use
tasklist /FI "windowtitle eq Title"
As addition to #Axel's answer with WMI - the same for description:
WMIC Process WHERE "Description='Only One'" GET ProcessID
And in VBS:
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set colItems = objWMIService.ExecQuery( _
"SELECT * FROM Win32_Process WHERE Description = 'My Desc'",,48)
For Each objItem in colItems
'Do Stuff
Next
Another possible value for description is the assembly's description which is retrievable with PowerShell. Use Get-Process to obtain the assembly path and retrieve its description with [System.Diagnostics.FileVersionInfo]::GetVersionInfo($File).FileDescription.

Related

How to get name of user account running a process on Windows command line?

I parse the output of wmic to get pid (process identifier), command line, etc. of a running process. Unfortunately user name (user executing this process) is missing from wmic output.
Is there a method to get the name of the user account?
Example wmic command:
wmic process where caption="explorer.exe"
Output:
Caption CommandLine CreationClassName CreationDate ...
explorer.exe C:\Windows\Explorer.EXE Win32_Process 20180214220330. ...
One possibility is using the command TASKLIST:
tasklist /V /FI "IMAGENAME eq explorer.exe"
Run in a command prompt window tasklist /? for help on this command which explains the used options.
The same command line for usage in a batch file with full qualified file name:
%SystemRoot%\System32\tasklist.exe /V /FI "IMAGENAME eq explorer.exe"

Stop all postgres services

I'm trying to write a cmd that will stop all instances of PostgreSQL on my server
net start | find /I "postgres"
returns all my running instance
I thought this would work
net start | find /I "postgres" | net stop
no luck
I also looked at
for /F "delims=" %A in ('net start | find /I "postgres"') do echo %A
There must be some way to do this
As far as I know the cmd does not provide text trimming function, right? I tried PowerShell with
net start | ? { $_.Contains("postgres")} | % { net stop $_.Trim() }
and works (with UAC of course).
To explain,
? is alias of Where-Object, whilst
% is alias of ForEach-Object, and
$_ is to mention piped element. In this case, every element from traversing array by ForEach-Object(%) is piped into inner expression.
These aliases and commands are available for a help text by Get-Help {func} or man {func}.
wmic service where name='lanmanserver' call stopservice
does lanmanserver, adjust to your program.
wmic /?
wmic service get /?
wmic service call /?
Or same objects in vbscript.
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_Service")
For Each objItem in colItems
'msgbox objItem.caption
If LCase(objItem.name) = "lanmanserver" then msgbox objItem.stopservice
Next

How to start a process when another process starts in Windows?

I'm trying to create a way that will check if a certain program is running - and if it is, launch another program.
This is my progress in BAT
#ECHO OFF
:LOOP
tasklist /nh /fi "imagename eq steam.exe" | find /i "steam.exe" >nul && START "" "C:\Program Files\TeamSpeak 3 Client\ts3client_win64.exe" || goto :LOOP
And I created a VBS that basically starts the BAT at Windows startup (this is only to make sure the batch file runs without a visible console window):
Set WshShell = CreateObject("WScript.Shell" )
WshShell.Run chr(34) & "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\if Steam running then TS.bat" & Chr(34), 0
Set WshShell = Nothing
My problem is that doing so, i get a incredibly high CPU usage (20 to 60% with a I5-4670k).
Have i done something wrong? Or can I improve the code anyhow? I was thinking about slowing the time where windows checks for the process (i.e. wait 2 sec then check) but I'm really new to coding and I don't have any idea on how to do so.
I know my English isn't perfect, excuse me.
EDIT: If it helps, my PC is running on Windows 10.
i get a incredibly high CPU usage
You need to give your computer a break between the checks. The timeout command interrupts batch execution for a configurable number of seconds:
#echo off
setlocal
set "FIND_STEAM=tasklist /nh /fi "imagename eq steam.exe" ^| find /i "steam.exe" ^> NUL"
set "START_TS=start "C:\Program Files\TeamSpeak 3 Client\ts3client_win64.exe""
:LOOP
timeout 5 > NUL
%FIND_STEAM% && %START_TS% || goto LOOP
EDIT
Here is bells-and-whistles sophisticated way of reacting to the start and termination of a process in Windows using VBScript.
It works with the WMI, a powerful framework that can do all kinds of things in Windows. Here we use it to listen to process creation and process termination events. (listening to events is a lot more efficient than polling all processes every second or so):
Option Explicit
Dim WMIService, ProcessNew, ProcessEnd
Dim computer, query, teamspeakPID
' create a WMI service object and ProcessNew / ProcessEnd event sinks
computer = "."
Set WMIService = GetObject("winmgmts:\\" & computer & "\root\CIMV2")
Set ProcessNew = WScript.CreateObject("WbemScripting.SWbemSink", "ProcessNew_")
Set ProcessEnd = WScript.CreateObject("WbemScripting.SWbemSink", "ProcessEnd_")
' we will be waiting for Win32_Process creation events and notify event sink "ProcessNew"
WMIService.ExecNotificationQueryAsync ProcessNew, _
"SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_Process'"
' we will also be waiting for Win32_Process deletion events and notify event sink "ProcessEnd"
WMIService.ExecNotificationQueryAsync ProcessEnd, _
"SELECT * FROM __InstanceDeletionEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_Process'"
' main loop: nothing to do, we just sit and wait
While True
Wscript.Sleep(500)
Wend
' function that handles "process created" events
Sub ProcessNew_OnObjectReady(latestEvent, asyncContext)
Dim process
If LCase(latestEvent.TargetInstance.Name) = "steam.exe" Then
' start TeamSpeak
Set process = GetObject("winmgmts:Win32_Process")
process.Create "C:\Program Files\TeamSpeak 3 Client\ts3client_win64.exe", null, null, teamspeakPID
End If
End Sub
' function that handles "process ended" events
Sub ProcessEnd_OnObjectReady(latestEvent, asyncContext)
Dim processList, process
If LCase(latestEvent.TargetInstance.Name) = "steam.exe" Then
' kill TeamSpeak (but only the one we started earlier)
Set processList = WMIService.ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'ts3client_win64.exe' AND ProcessId = " & teamspeakPID)
For Each process in processList
process.Terminate()
Next
End If
End Sub
As an exercise you can try to extend this so that it only starts TS when it's not already running.
Further reading:
Technet "Doctor Scripto's Script Shop" column
WMI asynchronous event monitoring with VBScript
Out of Sync: The Return of Asynchronous Event Monitoring
MSDN
The Win32_Process Class
Create method of the Win32_Process class
Terminate method of the Win32_Process class
SWbemServices.ExecNotificationQueryAsync method

Windows command for memory utilization % for particular service

Use wmic to capture the percentage of cpu usage for a specific service, but wish the same to determine my memory usage, is it possible to add the same line ?:
wmic path Win32_PerfFormattedData_PerfProc_Process get
Name,PercentProcessorTime | findstr /i /c:w3wp
Or it needs to be in a different line?
command with which I can make that query?
Tks for your help!!
This works in Windows CMD prompt,
tasklist /fi "services eq ServiceName"
Put your service name in 'ServiceName'
I am not sure if this is what you are asking.

Shutting down a windows process from 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.

Resources