- 1 year ago
Windows Ruby get PID from process name
In Ruby on Windows, you can get the PID (Process ID) from a process name using the win32ole
library, which provides access to Windows COM objects. Here's an example code snippet that demonstrates how to achieve this:
rubyrequire 'win32ole'
def get_pid_from_process_name(process_name)
wmi = WIN32OLE.connect("winmgmts://")
query = "SELECT ProcessId FROM Win32_Process WHERE Name='#{process_name}'"
result = wmi.ExecQuery(query)
if result.Count > 0
return result.each.first.ProcessId
else
return nil
end
end
# Example usage:
pid = get_pid_from_process_name("notepad.exe")
if pid.nil?
puts "Process not found"
else
puts "Process ID: #{pid}"
end
In this code, we use the win32ole
library to connect to the Windows Management Instrumentation (WMI) and execute a WMI query to retrieve the Process ID (ProcessId
) of the specified process name. The get_pid_from_process_name
function takes the process name as an argument and returns the PID of the first matching process or nil
if no matching process is found.
Note that the process name should include the file extension (e.g., "notepad.exe"). You can modify the code according to your specific process name.
Please make sure to install the win32ole
gem if you haven't already done so by running gem install win32ole
.
Keep in mind that this solution relies on Windows-specific functionality and may not work on non-Windows platforms.