#!/Perl
#   ProcList.pl
#   -----------
#   This script will display the list of current processes along with
#   the process's PID and binary path.
#   Syntax:
#       perl ProcList.pl [Machine Name]
#
#   Examples:
#       perl ProcTree 
#       perl ProcTree.pl \\server 
#
#   2002.01.20 rothd@roth.net
#
#   Permission is granted to redistribute and modify this code as long as 
#   the below copyright is included.
#
#   Copyright © 2002 by Dave Roth
#   Courtesty of Roth Consulting
#   http://www.roth.net/
#
#   Just added a LOG file output ... and 'standardised' the listing ...
#   geoff mclane - http://geoffmclane.com - 2006-06-14
#
use Win32::OLE qw( in );
use Win32::OLE::Variant;

$Machine = "\\\\.";
$Machine = shift @ARGV if( $ARGV[0] =~ /^\\\\/ );

# WMI Win32_Process class
$CLASS = "winmgmts:{impersonationLevel=impersonate}$Machine\\Root\\cimv2";
$count = 0;

# LOG FILE STUFF
my $write_log = 0;
my $outfile = "temp.$0.txt";
#my $LOG = new FileHandle ">$outfile"; 
my ($LOG); 
if ( open( $LOG, ">$outfile" ) ) {
###if ($LOG) {
    $write_log = 1;
	###select $LOG;
} else {
    $write_log = 0;
    prt( "WARNING: Unable to open $outfile LOG ...\n" );
}


$WMI = Win32::OLE->GetObject( $CLASS ) || die;
prt( "No   ID      Name                      Path (if any)\n" );
foreach my $Proc ( sort {lc $a->{Name} cmp lc $b->{Name}} in( $WMI->InstancesOf( "Win32_Process" ) ) )
{
	$count++;
	## printf( "%5d) %s ", $Proc->{ProcessID}, "\u$Proc->{Name}" );
	## print "( $Proc->{ExecutablePath} )" if( "" ne $Proc->{ExecutablePath} );
	## print "\n" ;
	$msg = "$count ";
	while(length($msg) < 4) { $msg .= ' '; }
	$msg .= " " . $Proc->{ProcessID};
	while(length($msg) < 12) { $msg .= ' '; }
	$msg .= " " . $Proc->{Name};
	while(length($msg) < 38) { $msg .= ' '; }
	$msg .= " " . $Proc->{ExecutablePath};
	$msg .= "\n";
	prt( $msg );
}

prt("Done enumeration of $count running processes ...\n");


################################
### output and log file
sub wlog {
	my $ml = shift;
	print $LOG $ml;
}

sub prt {
	my $m = shift;
	if ($write_log) {
		wlog($m);
	}
	print STDOUT $m;
}

sub mydie {
	my $msg = shift;
	if ($write_log) {
		wlog($msg);
	}
	die $msg;
}

sub close_log {
	if ($write_log) {
		prt( "Closing LOG file, and passing to 'system($outfile)'\nMay need to CLOSE notepad to continue ...\n" );
		close( $LOG );
		system( $outfile );
	}
}

