Listing Windows processes with Win32::Process::List

This article explains how to get a list of processes from Windows using Perl and the CPAN module Win32::Process::List. The following Perl script for Windows

#! perl
use warnings;
use strict;
use Win32::Process::List;
my $P = Win32::Process::List->new(); 
my %list = $P->GetProcesses(); 
foreach my $pid ( sort {$a <=> $b} keys %list ) {
    my $name = $list{$pid};
    print "$pid\t$name\n";
}
produces output like this:
0	[System Process]
4	System
200	taskeng.exe
432	smss.exe
448	svchost.exe
500	csrss.exe
504	RTNICDiag.exe
544	csrss.exe

The process ID number and name of each process is printed.

Notes: sort {$a <=> $b} sorts the keys into numerical order.

Using the process list

The list of processes can be used for other purposes. Here is a script which halts all instances of a particular program, in this case "chrome.exe", which is the Google Chrome web browser.

#! perl
use warnings;
use strict;
use Win32::Process::List;
use Win32::Process;
my $P = Win32::Process::List->new();
my %list = $P->GetProcesses();
foreach my $pid ( keys %list ) {
    my $name = $list{$pid};
    if ($name =~ /chrome\.exe/) {
        my $exitcode;
        Win32::Process::KillProcess ($pid, \$exitcode);
    }
}
This also makes use of Win32::Process for its "KillProcess" function, which halts the process identified by $pid.

Notes: The variable $exitcode is necessary to call the function. Its value is ignored.

Other links

See also my review of Win32::Process::List on CPAN Ratings for more detailed information about the module.
Copyright © Ben Bullock 2009-2014. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com). / Privacy / Disclaimer