#!C:/ActivePerl/bin/perl.exe use strict; use warnings; use Win32::OLE qw/in/; use Getopt::Long; # #How to run a process on a remote workstation (NT/2K) # my ($remote_computer, $command_path, $help); GetOptions ('r:s'=>\$remote_computer, 'c:s'=>\$command_path, 'h' =>\$help ) or warn("Couldn't read arguments.\n"); help_and_exit() if ($help); help_and_exit() if (!defined($remote_computer) || !defined($command_path) ); my $wmihandle = Win32::OLE->GetObject( "winmgmts:{impersonationLevel=impersonate,(security)}//$remote_computer\\root\\cimv2"); my $wmiprocesses = Win32::OLE->GetObject( "winmgmts:{impersonationLevel=impersonate,(security)}//$remote_computer\\root\\cimv2:Win32_Process"); #Is the process running already? unless ( cmd_is_running($wmihandle,$command_path) ) { print "$command_path is not already running.\n"; } #This doesn't seem to be necessary but it's in the docs! #http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/create_method_in_class_win32_process.asp my $Startup_Class = $wmihandle->Get("Win32_ProcessStartup"); my $Startup_Config = $Startup_Class->SpawnInstance_ ; my ($error, $pid, $startup_folder); $startup_folder="\\\\cntr035533\\c\$\\TEMP\\"; #The Create() method returns 0 on success if (0 == $wmiprocesses->Create($command_path) ) { $pid = $wmiprocesses->{'ProcessID'}; if (! $pid) { $pid = " [PID not available from Win32_Process.ProcessID]"; } print "Successfully started command with pid $pid\n"; }else{ print "Failed to create process with Win32_Process.Create(cmd)\n"; print "Trying Win32_Process.Create(cmdpath, startup, Win32_ProcessStartup, processid)\n"; $error = $wmiprocesses->Create($command_path,$startup_folder,$Startup_Config,$pid); #Error codes are 'explained' at the msdn link above. if ($error) { print "$command_path failed to start with WMI err: $error\n"; }else{ print "Started $command_path at 2nd attempt.\n"; } } #Check to see that the process is running. unless ( cmd_is_running($wmihandle,$command_path) ) { print "$command_path doesn't appear to be running.\n"; } #--- SUBS --- sub cmd_is_running{ my ($wmi,$cmd) = @_; return undef if not defined($wmi); return undef if not defined($cmd); my $cmdname; if ( $cmd=~ /(?:\\|\/)*([^\\\/]+)$/ ) { $cmdname=uc($1); }else{ print "Failed to get command name from $cmd\n"; return 0; } my $message = ''; #Ask the WMI Class for a list of Processes foreach my $process (in($wmihandle->InstancesOf("Win32_Process"))) { if (uc($process->{'Name'}) eq $cmdname ) { $message .= "$cmdname is running with PID = " . $process->{'ProcessID'} . "\n"; } } if ($message) { print $message return 1; } return 0; } sub help_and_exit { print < -c [Remember to use quotes if there are spaces!] -h print this and exit. EOF exit(1); } __END__