Set reliable time source (Perl)

This code can be found in Chapter 3 of Active Directory Cookbook, 2nd edition

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.

# Replace <PDCEmulatorName> with the DNS name of the PDC Emulator
# and <TimeServerNameOrIP> with the DNS name or IP address of the 
# reliable time source.

# ---------------------------------------------------------------
# Adapted from VBScript code contained in the book:
#      "Active Directory Cookbook" by Robbie Allen
# Publisher: O'Reilly and Associates
# ISBN: 0-596-00466-4
# Book web site: http://rallenhome.com/books/adcookbook/code.html
# ---------------------------------------------------------------

# ------ SCRIPT CONFIGURATION ------
my $strPDC = "<PDCEmulatorName>";            # e.g. dc01.rallencorp.com
my $strTimeServer = "<TimeServerNameOrIP>";  # e.g. ntp01.rallencorp.com
# ------ END CONFIGURATION ---------
use Win32::OLE;
$Win32::OLE::Warn = 3;
use Win32::OLE::Variant;

my $strTimeServerReg = 'SYSTEM\CurrentControlSet\Services\W32Time\Parameters';
my $HKLM = 0x80000002;
my $objReg = Win32::OLE->GetObject("winmgmts:\\\\$strPDC\\root\\default:StdRegProv");

my $strCurrentServer = Variant(VT_BSTR | VT_BYREF, "");
$objReg->GetStringValue($HKLM, $strTimeServerReg, "ntpserver", $strCurrentServer);
print "Current Value: $strCurrentServer\n";

$objReg->SetStringValue($HKLM, $strTimeServerReg, "ntpserver", $strTimeServer);
$objReg->SetStringValue($HKLM, $strTimeServerReg, "type", "NTP");

$strCurrentServer = Variant(VT_BSTR | VT_BYREF, "");
$objReg->GetStringValue($HKLM, $strTimeServerReg, "ntpserver", $strCurrentServer);
print "New Value: $strCurrentServer\n";

# Restart Time Service
my $objService = Win32::OLE->GetObject("winmgmts:\\\\" . $strPDC .
                           "\\root\\cimv2:Win32_Service='W32Time'");
print "Stopping ", $objService->Name,"\n";
$objService->StopService();

sleep 2;  # Sleep for 2 seconds to give service time to stop

print "Starting ", $objService->Name,"\n";
$objService->StartService();

This code has been viewed 1477 times.

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