FeraPapaLeguas
FeraPapaLeguas

Reputation: 13

What is the Windows terminal command to check if a program is running?

I would like to create a Windows script that checks if a program "anyprogram.exe" is running. If the condition is true, it ends the process of that program.

How can I do this?

Upvotes: 0

Views: 280

Answers (3)

mklement0
mklement0

Reputation: 437428

Use the Get-Process cmdlet in combination with Stop-Process:

# Note: Do NOT include ".exe" in the process name.
Get-Process -Name anyprogram -ErrorAction Ignore | Stop-Process

Note that Stop-Process forcefully stops (kills) a process, without giving it a chance to shut down gracefully.

If you need graceful termination - which may or may not be honored by the target process, however - use the standard Windows taskkill.exe utility (whose /f switch can be used to request forceful termination):

Get-Process -Name anyprogram -ErrorAction Ignore |
  ForEach-Object { taskkill /pid $_.Id }

If - potentially forceful - termination must be guaranteed, try graceful termination first, then - after a timeout - fall back to forceful termination - see this answer.

Upvotes: 1

CA Legendre
CA Legendre

Reputation: 1

I've done things within this realm years ago but I've been so heavily into my Mac world now that I'm hoping this is up to date enough or helpful.

Closing an app "gracefully" with WM_CLOSE:

$src = @'
using System;
using System.Runtime.InteropServices;
public static class Win32 {
    public static uint WM_CLOSE = 0x10;

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
    public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}
'@

Add-Type -TypeDefinition $src
$zero = [IntPtr]::Zero
$p = @(Get-Process Notepad)[0]
[Win32]::SendMessage($p.MainWindowHandle, [Win32]::WM_CLOSE, $zero, $zero) > $null

Also, I found this post I had bookmarked, which just might be helpful in the sense of the "checking to see" if the app is running. Stack Overflow: Continuously check if a process is running

Upvotes: 0

theClaw
theClaw

Reputation: 31

(Get-Process | Select-Object ProcessName | Where { $_.ProcessName -eq "anyprogram" }).Count -gt 0

Gets a list of processes running, filters on the name, counts the number of programs running with that name. If that number is greater than zero then the return value is true. If that number is zero then the return value is false.

A word of caution: omit the .exe extension in the comparison $_.ProcessName -eq "anyprogram" because Get-Process omits the ".exe" extension from results.

Upvotes: 0

Related Questions