Run a program as a service (Perl)

This code can be found in Chapter 10 of Windows XP Cookbook

Purchase XP Cookbook or Networking Recipes for only $25 plus shipping! While supplies last.

Find out how to download all of the Perl code from this site.

# From the book "Windows XP Cookbook"
# ISBN: 0596007256

# ------ SCRIPT CONFIGURATION ------

use Win32::OLE;

$strComputer = '.';
$strSvcName = 'MyMonitor';
$strSrvAnyPath = 'c:\\Windows Resource Kits\\Tools\\srvany.exe';
$strPerlPath = 'c:\\perl\\bin\\perl.exe';
$strPerlScript = 'c:\\scripts\\monitor.pl';
# ------ END CONFIGURATION ---------
use constant HKLM => 0x80000002;

# Service Type
use constant KERNEL_DRIVER => 1;
use constant FS_DRIVER => 2;
use constant ADAPTER => 4;
use constant RECOGNIZER_DRIVER => 8;
use constant OWN_PROCESS => 16;
use constant SHARE_PROCESS => 32;
use constant INTERACTIVE_PROCESS => 256;

$INTERACT_WITH_DESKTOP = 0;

# Error Control 
use constant NOT_NOTIFIED => 0;
use constant USER_NOTIFIED => 1;
use constant SYSTEM_RESTARTED => 2;
use constant SYSTEM_STARTS => 3;

$objWMI = Win32::OLE->GetObject('winmgmts:\\\\' . $strComputer . '\\root\\cimv2');
$objService = $objWMI->Get('Win32_Service');
$intRC = $objService->Create($strSvcName, $strSvcName, $strSrvAnyPath, OWN_PROCESS, !$_NOTIFED, 'Automatic', $INTERACT_WITH_DESKTOP, 'NT AUTHORITY\\LocalService', '');
if ($intRC > 0) {
    print 'Error creating service: ' . $intRC, "\n";
    exit 0;
}
else {
    print "Successfully created service\n";
}

$strKeyPath = 'SYSTEM\\CurrentControlSet\\Services\\' . $strSvcName . '\\Parameters';
$objReg = Win32::OLE->GetObject('winmgmts:\\\\' . $strComputer . '\\root\\default:StdRegProv');
$objReg->CreateKey(HKLM, $strKeyPath);
$objReg->SetStringValue(HKLM, $strKeyPath, 'Application', $strPerlPath);
$objReg->SetStringValue(HKLM, $strKeyPath, 'AppParameters', $strPerlScript);
print "Created registry values\n";

$objService = $objWMI->Get('Win32_Service.Name=\'' . $strSvcName . '\'');
$intRC = $objService->StartService;
if ($intRC > 0) {
    print 'Error starting service: ' . $intRC, "\n";
}
else {
    print "Successfully started service\n";
}

This code has been viewed 3010 times.

New from the creators of TechTasks.com: StatSheet.com