Friday, October 07, 2011

Ruby script to list process info in Windows

Below is a Ruby script to list process id and its command line in Windows.

To run it:
ruby pid.rb <process-name>
ie: ruby pid.rb java: will list java.exe and javaw.exe processes

class ProcessInfo
  attr_accessor :cmdLine, :pid
  def self.parseWmic(cmd)
    result = `#{cmd}`
    raise("Error: " + result) unless $? == 0
    processes = []
    pinfo = nil
    result.split(/\r?\n/).each do |line|
      next if line =~ /^\s*$/
      if line =~ /CommandLine=(.*)/i
        pinfo =
        pinfo.cmdLine = $1
      elsif line =~ /ProcessId=(\d+)/i = $1
        processes << pinfo unless == $$.to_i
    return processes
  def self.queryProcess(processName)
    return self.parseWmic("wmic process where \"name like '" + processName + 
                "%'\" get ProcessID,Commandline /format:list")
  def self.queryJavaProcess
    return self.queryProcess('java')
  def to_s
    @pid.to_s + " " + @cmdLine

puts ProcessInfo.queryProcess(ARGV[0])

Thursday, October 06, 2011

Equivalent of ps -ef | grep java in Windows

If you want to list a process and its command line, process id in Windows, this is the command:

 wmic process where "name='java.exe'" get ProcessID, Commandline /format:list

That is the equivalent of "ps -ef | grep java" in Linux. Then you could use taskkill /f /pid <PID> to kill it.