Use perl script to mange windows service: get status, start, stop and restart a Windows service

No GoodNeed ImprovementOKGoodExcellent (3 votes, average: 3 out of 5)
Loading ... Loading ...

If you want to use Perl script and windows scheduler to stop, start, restart a service at specific time, here is a script (based on Win32::OLE) you can use:

use Win32::Service;
use Win32::OLE;
my $hostName= $ARGV[0];
my $serviceName=$ARGV[1];
my $command =$ARGV[2];
my $command2 =$ARGV[3];

if ($#ARGV <2)
{
print “Usage: $0 hostName serviceName command[stop|start|restart|start_if_not_running] command2 \n”;
exit (0);
}

%status =(1 => 'STOPPED',
2 => ‘START_PENDING’,
3 => ‘STOP_PENDING’,
4 => ‘RUNNING’,
5 => ‘CONTINUE_PENDING’,
6 => ‘PAUSE_PENDING’,
7 => ‘PAUSED’,
8 => ‘ERROR’);

$ADsPath = "WinNT://$hostName/$serviceName,service";
$s = Win32::OLE->GetObject($ADsPath) or die “Unable to retrieve the object for $ADsPath\n”;
print $hostName .” | “. $serviceName .”: “. $status{$s->{status}} . “\n”;

my $cur_status = $status{$s->{status}};
if ( $command eq “stop”)
{
$s->Stop();
}
if ( $command eq “start”)
{
$s->Start();
}

if ( $command eq "restart")
{
$s->Stop();
sleep(60);
$s->Start();
}

if ( $command eq "start_if_not_running" && $cur_status ne 'RUNNING' )
{
$s->Start();
}

sleep(30);

$cur_status = $status{$s->{status}};
print $hostName .” | “. $serviceName .”: “. $cur_status . “\n”;

$hostName=lc($hostName);

if ($hostName eq "localhost")
{
if (($command eq ’start’ || $command eq ‘restart’ || $command eq ’start_if_not_running’) && $cur_status ne ‘RUNNING’)
{
my $command=”net start $serviceName”;
system($command);
}
if ($command2 ne “” && $command ne “stop”)
{
sleep(30);
system($command2);
}
}

Popularity: 9%

1 Comment »

  1. efultz said,

    June 4, 2007 @ 11:37 am

    Is this script able to be run from a Linux box to manage a Windows service?

RSS feed for comments on this post · TrackBack URI

Leave a Comment

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word