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

Time:01-26

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related